package com.industrial.premu.service.impl;

import java.io.*;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import java.math.BigDecimal;
import java.util.*;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.tree.TreeUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.NumberUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.industrial.common.core.domain.R;
import com.industrial.common.core.utils.DateUtils;
import com.industrial.common.core.web.domain.AjaxResult;
import com.industrial.common.security.utils.DictUtils;
import com.industrial.common.security.utils.SecurityUtils;
import com.industrial.premu.domain.sqsj.PreMuImportBenefitEvaluationNo;
import com.industrial.premu.domain.vo.ExternalVo;
import com.industrial.premu.dto.PreMuAreaTreeDto;
import com.industrial.premu.dto.PreMuBenefitEvaluationDto;
import com.industrial.premu.dto.PreMuChartsDto;
import com.industrial.premu.domain.*;
import com.industrial.premu.domain.sqsj.PreMuImportCustomIndexLj;
import com.industrial.premu.mapper.*;
import com.industrial.premu.mapper.sqsj.PreMuImportBenefitEvaluationNoMapper;
import com.industrial.premu.mapper.sqsj.PreMuImportCustomIndexLjMapper;
import com.industrial.premu.vo.*;
import com.industrial.system.api.RemoteWhiteInfoService;
import com.industrial.system.api.domain.EmEnterpriseInformationCollection;
import com.industrial.system.api.model.LoginUser;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import com.industrial.premu.mapper.PreMuBenefitEvaluationMapper;
import com.industrial.premu.domain.PreMuBenefitEvaluation;
import com.industrial.premu.service.IPreMuBenefitEvaluationService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.servlet.http.HttpServletResponse;

/**
 * 亩产效益评价Service业务层处理
 *
 * @author ZHOU_S
 * @date 2024-01-25
 */
@Service
public class PreMuBenefitEvaluationServiceImpl implements IPreMuBenefitEvaluationService {

    private static final String CACHE_INDEXWEIGHT_KEY = "INDEXWEIGHT";
    private static final String CACHE_ADDSUBLIST_KEY = "ADDSUBLIST";
    private static final String CACHE_COMPANYADDLIST_KEY = "COMPANYADDLIST";
    private static final String CACHE_COMPANYSUBLIST_KEY = "COMPANYSUBLIST";
    private static final String CACHE_CUSTOM_INDICATOR_LIST_KEY = "CUSTOMINDICATORLIST";
    private static final String CACHE_CUSTOM_INDICATOR_VALUE_LIST_KEY = "CUSTOMINDICATORVALUELIST";


    @Autowired
    private PreMuUpshiftMapper preMuUpshiftMapper;

    @Autowired
    private PreMuImportBenefitEvaluationNoMapper preMuImportBenefitEvaluationNoMapper;

    @Autowired
    private PreMuBenefitEvaluationMapper preMuBenefitEvaluationMapper;
    @Autowired
    private PreMuCompanyInfoMapper preMuCompanyInfoMapper;

    @Autowired
    private PreMuImportCustomIndexLjMapper preMuImportCustomIndexLjMapper;

    @Autowired
    private PreMuIndexWeightMainMapper preMuIndexWeightMainMapper;

    @Autowired
    private PreMuCustomIndicatorMapper preMuCustomIndicatorMapper;

    @Autowired
    private PreMuRateMapper preMuRateMapper;

    @Autowired
    private PreMuBenefitEvaluationLogMapper preMuBenefitEvaluationLogMapper;

    @Autowired
    private RemoteWhiteInfoService remoteWhiteInfoService;

    @Autowired
    private PreMuBenefitEvaluationMapper2025  preMuBenefitEvaluationMapper2025;

    @Value("${excel.templat}")
    private String excelTemplat;


    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 查询亩产效益评价
     *
     * @param id 亩产效益评价主键
     * @return 亩产效益评价
     */
    @Override
    public PreMuBenefitEvaluation selectPreMuBenefitEvaluationById(String id) {
        return preMuBenefitEvaluationMapper.selectPreMuBenefitEvaluationById(id);
    }


    /**
     * 查询亩产效益评价列表
     *
     * @param preMuBenefitEvaluation 亩产效益评价
     * @return 亩产效益评价
     */
    @Override
    public List<PreMuBenefitEvaluation> selectPreMuBenefitEvaluationList(PreMuBenefitEvaluation preMuBenefitEvaluation) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        Set<String> roles = loginUser.getRoles();
        if (roles.contains("q_01_001")) {
            preMuBenefitEvaluation.setUscc(loginUser.getUsername());
        } else if (roles.contains("x_01_011") || roles.contains("along_yellow_river")) {
            String county = loginUser.getSysUser().getDistrict();
            preMuBenefitEvaluation.setCounty(county);
        } else if (roles.contains("s_01_011")) {
            String city = loginUser.getSysUser().getCity();
            preMuBenefitEvaluation.setCity(city);
            preMuBenefitEvaluation.setStatus("5");
        } else if (roles.contains("p_01_011")) {
            String province = loginUser.getSysUser().getProvince();
            preMuBenefitEvaluation.setProvince(province);
//            preMuBenefitEvaluation.setStatus("5");
        }

      /*  if(StringUtils.isNotBlank(preMuBenefitEvaluation.getYears())){
            preMuBenefitEvaluation.setYears(DateUtils);
        }*/
        PreMuBenefitEvaluationDto dto = new PreMuBenefitEvaluationDto();
        BeanUtil.copyProperties(preMuBenefitEvaluation, dto);
        List<PreMuBenefitEvaluation> preMuBenefitEvaluations = preMuBenefitEvaluationMapper.selectPreMuBenefitEvaluationList(dto);
        List<String> usccList = new ArrayList<>();
        if (preMuBenefitEvaluations != null && !preMuBenefitEvaluations.isEmpty()) {
            usccList = preMuBenefitEvaluations.stream().map(PreMuBenefitEvaluation::getUscc).collect(Collectors.toList());
        }

        if (usccList != null && !usccList.isEmpty()) {
            R<List<String>> listR = remoteWhiteInfoService.preMuExistWhiteByUscc(usccList);
            if (listR.getCode() == R.SUCCESS) {
                List<String> data = listR.getData();
                Set<String> whiteExist = new HashSet<>();
                if (data != null && !data.isEmpty()) {
                    whiteExist = data.stream().collect(Collectors.toSet());
                }

                for (PreMuBenefitEvaluation temp : preMuBenefitEvaluations) {
                    String uscc = temp.getUscc();
                    if (whiteExist.contains(uscc)) {
                        temp.setIsWhite("1");
                    } else {
                        temp.setIsWhite("0");
                    }
                }
            } else {
                for (PreMuBenefitEvaluation temp : preMuBenefitEvaluations) {
                    String uscc = temp.getUscc();
                    temp.setIsWhite("1");
                }
            }
        } else {
            for (PreMuBenefitEvaluation temp : preMuBenefitEvaluations) {
                String uscc = temp.getUscc();
                temp.setIsWhite("1");
            }
        }

        return preMuBenefitEvaluations;
    }

    @Override
    public List<PreMuBenefitEvaluation20250520> selectPreMuBenefitEvaluationList2025(PreMuBenefitEvaluation preMuBenefitEvaluation) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        Set<String> roles = loginUser.getRoles();
        if (roles.contains("q_01_001")) {
            preMuBenefitEvaluation.setUscc(loginUser.getUsername());
        } else if (roles.contains("x_01_011") || roles.contains("along_yellow_river")) {
            String county = loginUser.getSysUser().getDistrict();
            preMuBenefitEvaluation.setCounty(county);
        } else if (roles.contains("s_01_011")) {
            String city = loginUser.getSysUser().getCity();
            preMuBenefitEvaluation.setCity(city);
            preMuBenefitEvaluation.setStatus("5");
        } else if (roles.contains("p_01_011")) {
            String province = loginUser.getSysUser().getProvince();
            preMuBenefitEvaluation.setProvince(province);
//            preMuBenefitEvaluation.setStatus("5");
        }

      /*  if(StringUtils.isNotBlank(preMuBenefitEvaluation.getYears())){
            preMuBenefitEvaluation.setYears(DateUtils);
        }*/
        List<PreMuBenefitEvaluation20250520> preMuBenefitEvaluations = preMuBenefitEvaluationMapper2025.selectPreMuBenefitEvaluationList(preMuBenefitEvaluation);
        List<String> usccList = new ArrayList<>();
        if (preMuBenefitEvaluations != null && !preMuBenefitEvaluations.isEmpty()) {
            usccList = preMuBenefitEvaluations.stream().map(PreMuBenefitEvaluation20250520::getUscc).collect(Collectors.toList());
        }

        if (usccList != null && !usccList.isEmpty()) {
            R<List<String>> listR = remoteWhiteInfoService.preMuExistWhiteByUscc(usccList);
            if (listR.getCode() == R.SUCCESS) {
                List<String> data = listR.getData();
                Set<String> whiteExist = new HashSet<>();
                if (data != null && !data.isEmpty()) {
                    whiteExist = data.stream().collect(Collectors.toSet());
                }

                for (PreMuBenefitEvaluation20250520 temp : preMuBenefitEvaluations) {
                    String uscc = temp.getUscc();
                    if (whiteExist.contains(uscc)) {
                        temp.setIsWhite("1");
                    } else {
                        temp.setIsWhite("0");
                    }
                }
            } else {
                for (PreMuBenefitEvaluation20250520 temp : preMuBenefitEvaluations) {
                    String uscc = temp.getUscc();
                    temp.setIsWhite("1");
                }
            }
        } else {
            for (PreMuBenefitEvaluation20250520 temp : preMuBenefitEvaluations) {
                String uscc = temp.getUscc();
                temp.setIsWhite("1");
            }
        }

        return preMuBenefitEvaluations;
    }

    /**
     * 新增亩产效益评价
     *
     * @param preMuBenefitEvaluation 亩产效益评价
     * @return 结果
     */
    @Override
    public int insertPreMuBenefitEvaluation(PreMuBenefitEvaluation preMuBenefitEvaluation) {
        return preMuBenefitEvaluationMapper.insertPreMuBenefitEvaluation(preMuBenefitEvaluation);
    }

    /**
     * 修改亩产效益评价
     *
     * @param preMuBenefitEvaluation 亩产效益评价
     * @return 结果
     */
    @Override
    public int updatePreMuBenefitEvaluation(PreMuBenefitEvaluation preMuBenefitEvaluation) {
        return preMuBenefitEvaluationMapper.updatePreMuBenefitEvaluation(preMuBenefitEvaluation);
    }

    /**
     * 批量删除亩产效益评价
     *
     * @param ids 需要删除的亩产效益评价主键
     * @return 结果
     */
    @Override
    public int deletePreMuBenefitEvaluationByIds(String[] ids) {
        return preMuBenefitEvaluationMapper.deletePreMuBenefitEvaluationByIds(ids);
    }

    /**
     * 删除亩产效益评价信息
     *
     * @param id 亩产效益评价主键
     * @return 结果
     */
    @Override
    public int deletePreMuBenefitEvaluationById(String id) {
        return preMuBenefitEvaluationMapper.deletePreMuBenefitEvaluationById(id);
    }

    @Override
    public PreMuBenefitEvaluationVo getById(String id) {

        return preMuBenefitEvaluationMapper.getById(id);
    }

    /**
     * <p>
     * 一键试算<br/>
     * 获取试用统计信息
     * </p>
     *
     * @param preMuBenefitEvaluation companyType 企业类型
     * @return 平均值 中位数 区域指标
     */
    @Override
    public AjaxResult getTrialStatistics(PreMuBenefitEvaluationDto preMuBenefitEvaluation) {
        if (StringUtils.isBlank(preMuBenefitEvaluation.getCompanyType())) {
            return AjaxResult.warn("请选择企业类型");
        }
        preMuBenefitEvaluation.setCounty(SecurityUtils.getLoginUser().getSysUser().getDistrict());
        LocalDate localDate = LocalDate.now();
        preMuBenefitEvaluation.setYears(String.valueOf(localDate.getYear() - 1));
        if ("-1".equals(preMuBenefitEvaluation.getIndustry())) {
            PreMuIndexWeightMain preMuIndexWeightMain = new PreMuIndexWeightMain();
            preMuIndexWeightMain.setCompanyType(preMuBenefitEvaluation.getCompanyType());
            preMuIndexWeightMain.setCounty(preMuBenefitEvaluation.getCounty());
            preMuIndexWeightMain.setYear(preMuBenefitEvaluation.getYears());

            List<PreMuIndexWeightMain> preMuIndexWeightMains = preMuIndexWeightMainMapper.selectPreMuIndexWeightMainListNew(preMuIndexWeightMain);

            if (!CollectionUtils.isEmpty(preMuIndexWeightMains)) {
                List<String> industries = preMuIndexWeightMains.stream()
                        .map(PreMuIndexWeightMain::getIndustry)
                        .filter(industry -> !StringUtils.isEmpty(industry) && !"-1".equals(industry)) // 更新的过滤条件
                        .collect(Collectors.toList());

                if (!CollectionUtils.isEmpty(industries)) {
                    List<String> industryCodeList = new ArrayList<>();
                    for (String industryCode : industries) {
                        String[] codes = industryCode.split(",");
                        industryCodeList.addAll(Arrays.asList(codes));
                    }

                    preMuBenefitEvaluation.setExcludeIndustryList(industryCodeList);
                }
            }
        }
        preMuBenefitEvaluation.setExcludeCalculateTypeFlag(true);
        List<PreMuBenefitEvaluation> allSumScore = preMuBenefitEvaluationMapper.getAllSumScore(preMuBenefitEvaluation);
        if (allSumScore.size() == 0) {
            Map<String, Object> data = new HashMap<>();
            data.put("avg", new ArrayList<String>());
            data.put("median", new ArrayList<String>());
            data.put("sumList", new ArrayList<String>());
            return AjaxResult.success(data);
        }


        //查询指标管理中的权重和基准值
//        PreMuIndexWeightMain preMuIndexWeightMainQueryParams = new PreMuIndexWeightMain();
//        preMuIndexWeightMainQueryParams.setYear(preMuBenefitEvaluation.getYears());
//        preMuIndexWeightMainQueryParams.setCompanyType(preMuBenefitEvaluation.getCompanyType());
//        preMuIndexWeightMainQueryParams.setCounty(preMuBenefitEvaluation.getCounty());
//        preMuIndexWeightMainQueryParams.setPark(preMuBenefitEvaluation.getPark());
//        preMuIndexWeightMainQueryParams.setIndustry(preMuBenefitEvaluation.getIndustry());
//        PreMuIndexWeightMain preMuIndexWeightMain = preMuIndexWeightMainMapper.selectOne(preMuIndexWeightMainQueryParams);
//        Map<String, PreMuIndexWeightSub> preMuIndexWeightMap = new HashMap<>(16);
//        if (preMuIndexWeightMain != null && preMuIndexWeightMain.getPreMuIndexWeightSubList() != null && !preMuIndexWeightMain.getPreMuIndexWeightSubList().isEmpty()) {
//            List<PreMuIndexWeightSub> preMuIndexWeightSubList = preMuIndexWeightMain.getPreMuIndexWeightSubList();
//            preMuIndexWeightMap = preMuIndexWeightSubList.stream().collect(Collectors.toMap(PreMuIndexWeightSub::getIndexName, v -> v));
//        }
//        PreMuIndexWeightSub profitWeight = preMuIndexWeightMap.get("收入利润率");
//        //计算各指标的平均值
        List<String> avgList = new ArrayList<>();

        //收入利润率
//        Optional<BigDecimal> profitScoreOption = Optional.ofNullable(
//                allSumScore.stream()
//                        .map(i -> {
//                            // 获取 score8，默认为 0
//                            BigDecimal profitScore = Optional.ofNullable(i.getScore8())
//                                    .orElse(BigDecimal.ZERO);
//
//                            // 获取 profitWeight 的 indexValue 和 indexValueLine
//                            BigDecimal profitWeightBigDecimal = Optional.ofNullable(profitWeight)
//                                    .map(w -> Optional.ofNullable(w.getIndexValue())
//                                            .map(BigDecimal::new)
//                                            .orElse(BigDecimal.ZERO))
//                                    .orElse(BigDecimal.ZERO);
//
//                            BigDecimal profitBaseline = StringUtils.isBlank(profitWeight != null ? profitWeight.getIndexValueLine() : null)
//                                    ? BigDecimal.ZERO
//                                    : new BigDecimal(profitWeight.getIndexValueLine());
//
//                            String status = i.getStatus();
//                            BigDecimal resultScore = BigDecimal.ZERO;
//
//                            if (!"4".equals(status)) {
//                                // 计算差值
//                                BigDecimal subtractRange = profitScore.subtract(profitBaseline).abs();
//
//                                if (profitScore.compareTo(profitBaseline) < 0) { // 实际 < 基准值
//                                    BigDecimal fivePercent = new BigDecimal("5");
//                                    BigDecimal tenPercent = new BigDecimal("10");
//                                    BigDecimal twentyPercent = new BigDecimal("20");
//
//                                    if (subtractRange.compareTo(fivePercent) <= 0) {
//                                        resultScore = profitWeightBigDecimal.multiply(new BigDecimal("0.8"));
//                                    } else if (subtractRange.compareTo(tenPercent) <= 0) {
//                                        resultScore = profitWeightBigDecimal.multiply(new BigDecimal("0.6"));
//                                    } else if (subtractRange.compareTo(twentyPercent) <= 0) {
//                                        resultScore = profitWeightBigDecimal.multiply(new BigDecimal("0.4"));
//                                    }
//                                    // else: 差值 >= 20%，保持 0 分
//                                } else {
//                                    // 实际 >= 基准值，直接加分
//                                    resultScore = profitWeightBigDecimal;
//                                }
//                            } else {
//                                // status == "4" 时，仅当 baseline 不为 0 才加分
//                                if (profitBaseline.compareTo(BigDecimal.ZERO) != 0) {
//                                    resultScore = profitWeightBigDecimal;
//                                }
//                            }
//
//                            return resultScore;
//                        })
//                        .reduce(BigDecimal.ZERO, BigDecimal::add)
//        );
//        BigDecimal profitScoreResult = profitScoreOption.orElse(new BigDecimal(0));
        Optional<BigDecimal> profitScore = allSumScore.stream().map(i -> i.getScore8() == null ? BigDecimal.valueOf(0) : i.getScore8()).reduce(BigDecimal::add);
        BigDecimal profitScoreResult = profitScore.orElse(new BigDecimal(0));
        avgList.add(profitScoreResult.divide(BigDecimal.valueOf(allSumScore.size()), 2, BigDecimal.ROUND_HALF_UP).toString());
        //单位用地税收得分
//        Optional<BigDecimal> dwydssScore = allSumScore.stream().map(i -> i.getScore1() == null ? BigDecimal.valueOf(0) : i.getScore1()).reduce(BigDecimal::add);
//        BigDecimal dwydssScoreResult = dwydssScore.orElse(new BigDecimal(0));
//        avgList.add(dwydssScoreResult.divide(BigDecimal.valueOf(allSumScore.size()), 2, BigDecimal.ROUND_HALF_UP).toString());

        //单位能耗销售收入得分
        Optional<BigDecimal> dwnhxssrScore = allSumScore.stream().map(i -> i.getScore2() == null ? BigDecimal.valueOf(0) : i.getScore2()).reduce(BigDecimal::add);
        BigDecimal dwnhxssrScoreResult = dwnhxssrScore.orElse(new BigDecimal(0));
        avgList.add(dwnhxssrScoreResult.divide(BigDecimal.valueOf(allSumScore.size()), 2, BigDecimal.ROUND_HALF_UP).toString());

        //单位污染物排放销售收入得分
        Optional<BigDecimal> dwwrwpfxsScore = allSumScore.stream().map(i -> i.getScore3() == null ? BigDecimal.valueOf(0) : i.getScore3()).reduce(BigDecimal::add);
        BigDecimal dwwrwpfxsScoreResult = dwwrwpfxsScore.orElse(new BigDecimal(0));
        avgList.add(dwwrwpfxsScoreResult.divide(BigDecimal.valueOf(allSumScore.size()), 2, BigDecimal.ROUND_HALF_UP).toString());

        //研发经费投入强度得分
        Optional<BigDecimal> yfjftrqdScore = allSumScore.stream().map(i -> i.getScore4() == null ? BigDecimal.valueOf(0) : i.getScore4()).reduce(BigDecimal::add);
        BigDecimal yfjftrqdScoreResult = yfjftrqdScore.orElse(new BigDecimal(0));
        avgList.add(yfjftrqdScoreResult.divide(BigDecimal.valueOf(allSumScore.size()), 2, BigDecimal.ROUND_HALF_UP).toString());

        //全员劳动生产率得分
        Optional<BigDecimal> qyldsclScore = allSumScore.stream().map(i -> i.getScore5() == null ? BigDecimal.valueOf(0) : i.getScore5()).reduce(BigDecimal::add);
        BigDecimal qyldsclScoreResult = qyldsclScore.orElse(new BigDecimal(0));
        avgList.add(qyldsclScoreResult.divide(BigDecimal.valueOf(allSumScore.size()), 2, BigDecimal.ROUND_HALF_UP).toString());

        //单位用地销售收入得分
        Optional<BigDecimal> dwydxsScore = allSumScore.stream().map(i -> i.getScore7() == null ? BigDecimal.valueOf(0) : i.getScore7()).reduce(BigDecimal::add);
        BigDecimal dwydxsScoreResult = dwydxsScore.orElse(new BigDecimal(0));
        avgList.add(dwydxsScoreResult.divide(BigDecimal.valueOf(allSumScore.size()), 2, BigDecimal.ROUND_HALF_UP).toString());

        //单位水耗销售收入得分
        Optional<BigDecimal> dwshxsScore = allSumScore.stream().map(i -> i.getScore6() == null ? BigDecimal.valueOf(0) : i.getScore6()).reduce(BigDecimal::add);
        BigDecimal dwshxsScoreResult = dwshxsScore.orElse(new BigDecimal(0));
        avgList.add(dwshxsScoreResult.divide(BigDecimal.valueOf(allSumScore.size()), 2, BigDecimal.ROUND_HALF_UP).toString());



        //获取中位数
        List<String> medianList = new ArrayList<>();
        //利润
//        List<BigDecimal> score8List = allSumScore.stream().map(d -> {
//            // 获取 score8，默认为 0
//            BigDecimal profitScore = Optional.ofNullable(d.getScore8())
//                    .orElse(BigDecimal.ZERO);
//
//            // 获取 profitWeight 的 indexValue 和 indexValueLine
//            BigDecimal profitWeightBigDecimal = Optional.ofNullable(profitWeight)
//                    .map(w -> Optional.ofNullable(w.getIndexValue())
//                            .map(BigDecimal::new)
//                            .orElse(BigDecimal.ZERO))
//                    .orElse(BigDecimal.ZERO);
//
//            BigDecimal profitBaseline = StringUtils.isBlank(profitWeight != null ? profitWeight.getIndexValueLine() : null)
//                    ? BigDecimal.ZERO
//                    : new BigDecimal(profitWeight.getIndexValueLine());
//
//            String status = d.getStatus();
//            BigDecimal resultScore = BigDecimal.ZERO;
//
//            if (!"4".equals(status)) {
//                // 计算差值
//                BigDecimal subtractRange = profitScore.subtract(profitBaseline).abs();
//
//                if (profitScore.compareTo(profitBaseline) < 0) { // 实际 < 基准值
//                    BigDecimal fivePercent = new BigDecimal("5");
//                    BigDecimal tenPercent = new BigDecimal("10");
//                    BigDecimal twentyPercent = new BigDecimal("20");
//
//                    if (subtractRange.compareTo(fivePercent) <= 0) {
//                        resultScore = profitWeightBigDecimal.multiply(new BigDecimal("0.8"));
//                    } else if (subtractRange.compareTo(tenPercent) <= 0) {
//                        resultScore = profitWeightBigDecimal.multiply(new BigDecimal("0.6"));
//                    } else if (subtractRange.compareTo(twentyPercent) <= 0) {
//                        resultScore = profitWeightBigDecimal.multiply(new BigDecimal("0.4"));
//                    }
//                    // else: 差值 >= 20%，保持 0 分
//                } else {
//                    // 实际 >= 基准值，直接加分
//                    resultScore = profitWeightBigDecimal;
//                }
//            } else {
//                // status == "4" 时，仅当 baseline 不为 0 才加分
//                if (profitBaseline.compareTo(BigDecimal.ZERO) != 0) {
//                    resultScore = profitWeightBigDecimal;
//                }
//            }
//
//            return resultScore;
//        }).collect(Collectors.toList());
        List<BigDecimal> score8List = allSumScore.stream().map(d -> d.getScore8() == null ? BigDecimal.valueOf(0) : d.getScore8()).collect(Collectors.toList());
        medianList.add(median(score8List));
//        List<BigDecimal> score1List = allSumScore.stream().map(d -> d.getScore1() == null ? BigDecimal.valueOf(0) : d.getScore1()).collect(Collectors.toList());
//        medianList.add(median(score1List));
        List<BigDecimal> score2List = allSumScore.stream().map(d -> d.getScore2() == null ? BigDecimal.valueOf(0) : d.getScore2()).collect(Collectors.toList());
        medianList.add(median(score2List));
        List<BigDecimal> score3List = allSumScore.stream().map(d -> d.getScore3() == null ? BigDecimal.valueOf(0) : d.getScore3()).collect(Collectors.toList());
        medianList.add(median(score3List));
        List<BigDecimal> score4List = allSumScore.stream().map(d -> d.getScore4() == null ? BigDecimal.valueOf(0) : d.getScore4()).collect(Collectors.toList());
        medianList.add(median(score4List));
        List<BigDecimal> score5List = allSumScore.stream().map(d -> d.getScore5() == null ? BigDecimal.valueOf(0) : d.getScore5()).collect(Collectors.toList());
        medianList.add(median(score5List));

        List<BigDecimal> score7List = allSumScore.stream().map(d -> d.getScore7() == null ? BigDecimal.valueOf(0) : d.getScore7()).collect(Collectors.toList());
        medianList.add(median(score7List));

        List<BigDecimal> score6List = allSumScore.stream().map(d -> d.getScore6() == null ? BigDecimal.valueOf(0) : d.getScore6()).collect(Collectors.toList());
        medianList.add(median(score6List));


        //区域总指标
        List<String> sumList = new ArrayList<>();

        Optional<BigDecimal> useAreaSum = allSumScore.stream().map(d -> d.getSumArea() == null ? BigDecimal.valueOf(0) : d.getSumArea()).reduce(BigDecimal::add);
        Optional<BigDecimal> waterBureauSum = allSumScore.stream().map(d -> d.getWaterBureau() == null ? BigDecimal.valueOf(0) : d.getWaterBureau()).reduce(BigDecimal::add);
        //总税收
        Optional<BigDecimal> actualTax = allSumScore.stream().map(d -> d.getActualTax() == null ? BigDecimal.valueOf(0) : d.getActualTax()).reduce(BigDecimal::add);

        BigDecimal actualTaxSum = actualTax.orElse(new BigDecimal(0));
        BigDecimal areaSum = useAreaSum.orElse(new BigDecimal(0));
        BigDecimal waterBureau = waterBureauSum.orElse(new BigDecimal(0));
//        if (BigDecimal.valueOf(0).compareTo(areaSum) == 0) {
//            sumList.add("0.00");
//        } else {
//            sumList.add(actualTaxSum.divide(areaSum, 2, BigDecimal.ROUND_HALF_UP).toString());
//        }

        //指标：单位能耗销售收入  单位：万元/吨标准煤  计算方式：销售收入/总能耗
        //总销售收入
        Optional<BigDecimal> mainIncomeSum = allSumScore.stream().map(d -> {
            return d.getMainIncome() == null ? BigDecimal.valueOf(0) : d.getMainIncome();
        }).reduce(BigDecimal::add);
        BigDecimal incomeSum = mainIncomeSum.orElse(new BigDecimal(0));
        //利润总额
        Optional<BigDecimal> profitTotalSum = allSumScore.stream().map(d -> {
            return d.getProfitTotal() == null ? BigDecimal.valueOf(0) : d.getProfitTotal();
        }).reduce(BigDecimal::add);
        BigDecimal profitSum = profitTotalSum.orElse(new BigDecimal(0));
        if (BigDecimal.valueOf(0).compareTo(profitSum) == 0) {
            sumList.add("0.00");
        } else {
            sumList.add(profitSum.divide(incomeSum, 2, BigDecimal.ROUND_HALF_UP).toString());
        }
        //总能耗
        Optional<BigDecimal> totalUsedSum = allSumScore.stream().map(d -> {
            if (StringUtils.isNotBlank(d.getTotalUsed())) {
                return new BigDecimal(d.getTotalUsed());
            }
            return new BigDecimal(0);
        }).reduce(BigDecimal::add);
        BigDecimal userSum = totalUsedSum.orElse(new BigDecimal(0));
        if (BigDecimal.valueOf(0).compareTo(userSum) == 0) {
            sumList.add("0.00");
        } else {
            sumList.add(incomeSum.divide(userSum, 2, BigDecimal.ROUND_HALF_UP).toString());
        }

        //指标：单位污染物排放销售收入 单位：万元/当量吨  计算方式：销售收入/主要污染物排放总当量
        //总排放总当量
        Optional<BigDecimal> totalEquivalentSum = allSumScore.stream().map(d -> {
            if (StringUtils.isNotBlank(d.getTotalEquivalent())) {
                return new BigDecimal(d.getTotalEquivalent());
            }
            return new BigDecimal(0);
        }).reduce(BigDecimal::add);
        BigDecimal equivalentsum = totalEquivalentSum.orElse(new BigDecimal("0.00"));
        if (BigDecimal.valueOf(0).compareTo(equivalentsum) == 0) {
            sumList.add("0.00");
        } else {
            sumList.add(incomeSum.divide(equivalentsum, 2, BigDecimal.ROUND_HALF_UP).toString());
        }

        //指标：研发经费投入强度 单位：%   计算方式：研发经费支出/销售收入
        //总研发经费
        Optional<BigDecimal> rdFundsSum = allSumScore.stream().map(d -> {
            return d.getRdFunds() == null ? BigDecimal.valueOf(0) : d.getRdFunds();
        }).reduce(BigDecimal::add);
        BigDecimal fundsSum = rdFundsSum.orElse(new BigDecimal(0));
        if (BigDecimal.valueOf(0).compareTo(incomeSum) == 0) {
            sumList.add("0.00");
        } else {
            BigDecimal score4Sum = fundsSum.divide(incomeSum, 5, BigDecimal.ROUND_HALF_UP);
            sumList.add(score4Sum.multiply(BigDecimal.valueOf(100)).setScale(2, BigDecimal.ROUND_HALF_UP).toString());
        }

        //指标：全员劳动生产率 单位：万元/人   计算方式：工业总产值（现价）/年平均职工人数
        //总工业总产值
        Optional<BigDecimal> industryOutputSum = allSumScore.stream().map(d -> {
            return d.getIndustryOutput() == null ? BigDecimal.valueOf(0) : d.getIndustryOutput();
        }).reduce(BigDecimal::add);
        BigDecimal outputSum = industryOutputSum.orElse(new BigDecimal(0));
        //总年平均职工人数
        Optional<Long> annualEmployeesSum = allSumScore.stream().map(d -> {
            return d.getAnnualEmployees() == null ? Long.valueOf(0) : d.getAnnualEmployees();
        }).reduce(Long::sum);
        Long employeesSum = annualEmployeesSum.orElse(0L);
        if (Long.valueOf(0).compareTo(employeesSum) == 0) {
            sumList.add("0.00");
        } else {
            sumList.add(outputSum.divide(BigDecimal.valueOf(employeesSum), 2, BigDecimal.ROUND_HALF_UP).toString());
        }

        //指标：单位用的销售收入  单位：万元/亩  计算方式：销售收入/用的
        //总销售收入
        if (BigDecimal.valueOf(0).compareTo(areaSum) == 0) {
            sumList.add("0.00");
        } else {
            sumList.add(incomeSum.divide(areaSum, 2, BigDecimal.ROUND_HALF_UP).toString());
        }

        if (BigDecimal.valueOf(0).compareTo(waterBureau) == 0) {
            sumList.add("0.00");
        } else {
            sumList.add(waterBureau.divide(waterBureau, 2, BigDecimal.ROUND_HALF_UP).toString());
        }

        Map<String, Object> data = new HashMap<>();
        data.put("avg", avgList.isEmpty() ? new ArrayList<String>() : avgList);
        data.put("median", medianList.isEmpty() ? new ArrayList<String>() : medianList);
        data.put("sumList", sumList.isEmpty() ? new ArrayList<String>() : sumList);
        return AjaxResult.success(data);
    }

    /**
     * <p>
     * 一键试算
     * </p >
     * <p>
     * 获取企业的单项指标值
     * </p >
     *
     * @param preMuBenefitEvaluation
     * @return
     */
    @Override
    public com.github.pagehelper.Page<Map<String, String>> getEnterSingleIndexScore(PreMuBenefitEvaluationDto preMuBenefitEvaluation) {
        //查询待试算的数据
        if ("-1".equals(preMuBenefitEvaluation.getIndustry())) {
            PreMuIndexWeightMain preMuIndexWeightMain = new PreMuIndexWeightMain();
            preMuIndexWeightMain.setCompanyType(preMuBenefitEvaluation.getCompanyType());
            preMuIndexWeightMain.setCounty(preMuBenefitEvaluation.getCounty());
            preMuIndexWeightMain.setYear(preMuBenefitEvaluation.getYears());


            List<PreMuIndexWeightMain> preMuIndexWeightMains = preMuIndexWeightMainMapper.selectPreMuIndexWeightMainListNew(preMuIndexWeightMain);

            if (!CollectionUtils.isEmpty(preMuIndexWeightMains)) {
                List<String> industries = preMuIndexWeightMains.stream()
                        .map(PreMuIndexWeightMain::getIndustry)
                        .filter(industry -> !StringUtils.isEmpty(industry) && !"-1".equals(industry)) // 更新的过滤条件
                        .collect(Collectors.toList());

                if (!CollectionUtils.isEmpty(industries)) {
                    List<String> industryCodeList = new ArrayList<>();
                    for (String industryCode : industries) {
                        String[] codes = industryCode.split(",");
                        industryCodeList.addAll(Arrays.asList(codes));
                    }

                    preMuBenefitEvaluation.setExcludeIndustryList(industryCodeList);
                }
            }
        }
        preMuBenefitEvaluation.setExcludeCalculateTypeFlag(true);
        PageHelper.startPage(preMuBenefitEvaluation.getPageNum() != null ? preMuBenefitEvaluation.getPageNum() : 1, preMuBenefitEvaluation.getPageSize() != null ? preMuBenefitEvaluation.getPageSize():10);
        List<PreMuBenefitEvaluation> dataList = preMuBenefitEvaluationMapper.selectPreMuBenefitEvaluationList(preMuBenefitEvaluation);

        if (dataList == null || dataList.isEmpty()) {
            return new com.github.pagehelper.Page<Map<String, String>>();
        }

        long count = dataList.stream().filter(k -> !StringUtils.equals(k.getStatus(), "已核实")).count();

        if (count > 0) {
            throw new RuntimeException(String.format("存在未核实数据%d条", count));
        }

        //计算需要权重和基准值，查询基准值和权重
        //1.查询指标管理中的权重和基准值
        PreMuIndexWeightMain preMuIndexWeightMainQueryParams = new PreMuIndexWeightMain();
        preMuIndexWeightMainQueryParams.setYear(preMuBenefitEvaluation.getYears());
        preMuIndexWeightMainQueryParams.setCompanyType(preMuBenefitEvaluation.getCompanyType());
        preMuIndexWeightMainQueryParams.setCounty(preMuBenefitEvaluation.getCounty());
        preMuIndexWeightMainQueryParams.setPark(preMuBenefitEvaluation.getPark());
        preMuIndexWeightMainQueryParams.setIndustry(preMuBenefitEvaluation.getIndustry());
        PreMuIndexWeightMain preMuIndexWeightMain = preMuIndexWeightMainMapper.selectOne(preMuIndexWeightMainQueryParams);


        if (preMuIndexWeightMain == null || preMuIndexWeightMain.getPreMuIndexWeightSubList() == null || preMuIndexWeightMain.getPreMuIndexWeightSubList().isEmpty()) {
            StringBuilder sb = new StringBuilder(String.format("%s年当前区县没有设置", preMuBenefitEvaluation.getYears()));
            if(!StringUtils.isEmpty(preMuBenefitEvaluation.getCompanyType())){
                String enterType = StringUtils.equals(preMuBenefitEvaluation.getCompanyType(), "2") ? "规下企业" : "规上企业";
                sb.append(enterType);
            }
            if(!StringUtils.isEmpty(preMuBenefitEvaluation.getIndustry())){
                sb.append(preMuBenefitEvaluation.getIndustry());
            }
            if(!StringUtils.isEmpty(preMuBenefitEvaluation.getPark())){
                sb.append(preMuBenefitEvaluation.getPark());
            }
            sb.append("权重");
            throw new RuntimeException(sb.toString());
        }

        //取出待试算企业的ID
        List<String> dssCompanyIds = dataList.stream().map(PreMuBenefitEvaluation::getCompanyId).collect(Collectors.toList());

        //查询企业的自定义指标值,通过待试算的企业ID
        List<PreMuImportCustomIndexLj> companyCustomIndexValueList = preMuImportCustomIndexLjMapper.selectPreMuimportCustomIndexLjListByCompanyId(dssCompanyIds);
        //企业ID对应的自定义指标值
        Map<String, List<PreMuImportCustomIndexLj>> companyToCustomIndexMap = new HashMap<>();
        if (companyCustomIndexValueList != null && !companyCustomIndexValueList.isEmpty()) {
            companyToCustomIndexMap = companyCustomIndexValueList.stream().collect(Collectors.groupingBy(PreMuImportCustomIndexLj::getEnterId));
        }

        //查询自定义指标的信息，当前年度、当前区县、当前企业类型
        PreMuCustomIndicator queryParams = new PreMuCustomIndicator();
        queryParams.setYear(preMuBenefitEvaluation.getYears());
        queryParams.setCounty(preMuBenefitEvaluation.getCounty());
        queryParams.setCompanyType(preMuBenefitEvaluation.getCompanyType());
        List<PreMuCustomIndicator> preMuCustomIndicators = preMuCustomIndicatorMapper.selectPreMuCustomIndicatorList(queryParams);


//        if(!companyToCustomIndexMap.isEmpty()){
//            if(preMuCustomIndicators == null || preMuCustomIndicators.isEmpty()){
//                String enterType = StringUtils.equals(preMuBenefitEvaluation.getCompanyType(),"2") ? "规下企业" : "规上企业";
//                throw new RuntimeException(String.format("%s年当前区县没有设置%s自定义指标",preMuBenefitEvaluation.getYears(),enterType));
//            }
//        }


        Map<String, PreMuCustomIndicator> customYsData = new HashMap<>();

        if (preMuCustomIndicators != null && !preMuCustomIndicators.isEmpty()) {
            customYsData = preMuCustomIndicators.stream().collect(Collectors.toMap(PreMuCustomIndicator::getId, v -> v));
        }

        //如果指标管理中的指标有数据，则将指标获取出来存到Map中
        /**
         * Key：指标名称，value:指标值
         */
        Map<String, PreMuIndexWeightSub> preMuIndexWeightMap = new HashMap<>(16);
        if (preMuIndexWeightMain != null && preMuIndexWeightMain.getPreMuIndexWeightSubList() != null && !preMuIndexWeightMain.getPreMuIndexWeightSubList().isEmpty()) {
            List<PreMuIndexWeightSub> preMuIndexWeightSubList = preMuIndexWeightMain.getPreMuIndexWeightSubList();
            preMuIndexWeightMap = preMuIndexWeightSubList.stream().collect(Collectors.toMap(PreMuIndexWeightSub::getIndexName, v -> v));
        }

        List<Map<String, String>> list = new ArrayList<>();

        BigDecimal zeroBigDecimal = new BigDecimal(0);

        //遍历待试算的数据
        for (PreMuBenefitEvaluation itemData : dataList) {
            Map<String, String> result = calculateScores(preMuBenefitEvaluation, companyToCustomIndexMap, customYsData, preMuIndexWeightMap, zeroBigDecimal, itemData);
            list.add(result);
        }

        //通过代码处理数据分页
        if (dataList instanceof Page) {
            Page page = (Page) dataList;
            int pageNum = page.getPageNum();
            int pageSize = page.getPageSize();
            long total = page.getTotal();
            com.github.pagehelper.Page<Map<String, String>> pp = new Page<>();
            pp.addAll(list);
            pp.setTotal(total);
            pp.setPageNum(pageNum);
            pp.setPageSize(pageSize);
            return pp;
        }
        return null;
    }

    /**
     * 计算结果的方法
     *
     * @param preMuBenefitEvaluation  传值的数据，没啥用
     * @param companyToCustomIndexMap
     * @param customYsData            自定义指标
     * @param preMuIndexWeightMap     指标管理的数据
     * @param zeroBigDecimal          为零的对像
     * @param itemData                当前企业的亩产数据
     * @return
     */
    private static Map<String, String> calculateScores(PreMuBenefitEvaluationDto preMuBenefitEvaluation,
                                                       Map<String, List<PreMuImportCustomIndexLj>> companyToCustomIndexMap,
                                                       Map<String, PreMuCustomIndicator> customYsData,
                                                       Map<String, PreMuIndexWeightSub> preMuIndexWeightMap,
                                                       BigDecimal zeroBigDecimal,
                                                       PreMuBenefitEvaluation itemData) {
        BigDecimal addScoreBigDecimal = itemData.getAddScore() == null ? new BigDecimal(0) : itemData.getAddScore();
        BigDecimal subScoreBigDecimal = itemData.getSubScore() == null ? new BigDecimal(0) : itemData.getSubScore();

        Map<String, String> result = new HashMap<>(16);
        result.put("year", preMuBenefitEvaluation.getYears());
        result.put("enterName", itemData.getCompanyName());
        BigDecimal sumScore = new BigDecimal(0);

//        //税收实际贡献
//        BigDecimal actualTax = itemData.getActualTax() == null ? new BigDecimal(0) : itemData.getActualTax();
//        //用地面积
//        BigDecimal sumArea = itemData.getSumArea() == null ? new BigDecimal(0) : itemData.getSumArea();
//        //销售收入
//        BigDecimal mainIncome = itemData.getMainIncome() == null ? new BigDecimal(0) : itemData.getMainIncome();
//        //总能耗
//        BigDecimal totalUsed = StringUtils.isBlank(itemData.getTotalUsed()) ? new BigDecimal(0) : new BigDecimal(itemData.getTotalUsed());
//        //主要污染排放量
//        BigDecimal totalEquivalent = StringUtils.isBlank(itemData.getTotalEquivalent()) ? new BigDecimal(0) : new BigDecimal(itemData.getTotalEquivalent());
//        //研发经费支出
//        BigDecimal rdFunds = itemData.getRdFunds() == null ? new BigDecimal(0) : itemData.getRdFunds();
//        //工业总产值
//        BigDecimal industryOutput = itemData.getIndustryOutput() == null ? new BigDecimal(0) : itemData.getIndustryOutput();
//        //用水量
//        BigDecimal waterBureau = itemData.getWaterBureau() == null ? new BigDecimal(0) : itemData.getWaterBureau();
//        //年平均职人数
//        BigDecimal annualEmployees = itemData.getAnnualEmployees() == null ? new BigDecimal(0) : new BigDecimal(itemData.getAnnualEmployees());

        //计算单位用地税收
//        BigDecimal dwydss = itemData.getScore1();
//        if (dwydss != null && preMuIndexWeightMap.containsKey("单位用地税收")) {
//            PreMuIndexWeightSub dwydssWeight = preMuIndexWeightMap.get("单位用地税收");
//            BigDecimal dwydssWeightBigDecimal = dwydssWeight.getIndexValue() == null ? new BigDecimal(0) : new BigDecimal(dwydssWeight.getIndexValue());
//            BigDecimal dwydssWeightValueLineBigDecimal = dwydssWeight.getIndexValueLine() == null ? new BigDecimal(0) : new BigDecimal(dwydssWeight.getIndexValueLine());
//
//            if (!dwydssWeightValueLineBigDecimal.equals(BigDecimal.ZERO)) {
//                BigDecimal resultValue = dwydss.divide(dwydssWeightValueLineBigDecimal, 2, BigDecimal.ROUND_HALF_UP).multiply(dwydssWeightBigDecimal);
//
//                if (resultValue.compareTo(new BigDecimal(0)) == -1) {
//                    resultValue = new BigDecimal(0);
//                }
//
//                if (resultValue.compareTo(dwydssWeightBigDecimal) == 1) {
//                    resultValue = dwydssWeightBigDecimal;
//                }
//                sumScore = sumScore.add(resultValue);
//                result.put("dwydss", resultValue.toString());
//            } else {
//                result.put("dwydss", zeroBigDecimal.toString());
//            }
//        } else {
//            result.put("dwydss", new BigDecimal(0).toString());
//        }

        //单位用地销售收入
//      BigDecimal dwydxssr = mainIncome.divide(sumArea,2,BigDecimal.ROUND_HALF_UP);
        BigDecimal dwydxssr = itemData.getScore7();
        if (dwydxssr != null && preMuIndexWeightMap.containsKey("单位用地营业收入")) {
            PreMuIndexWeightSub dwydxssrWeight = preMuIndexWeightMap.get("单位用地营业收入");
            BigDecimal dwydxssrWeightBigDecimal = dwydxssrWeight.getIndexValue() == null ? new BigDecimal(0) : new BigDecimal(dwydxssrWeight.getIndexValue());
            BigDecimal dwydxssrWeightValueLineBigDecimal = dwydxssrWeight.getIndexValueLine() == null ? new BigDecimal(0) : new BigDecimal(dwydxssrWeight.getIndexValueLine());
            if (!dwydxssrWeightValueLineBigDecimal.equals(BigDecimal.ZERO)) {
                BigDecimal resultValue = dwydxssr.divide(dwydxssrWeightValueLineBigDecimal, 2, BigDecimal.ROUND_HALF_UP).multiply(dwydxssrWeightBigDecimal);

                if (resultValue.compareTo(new BigDecimal(0)) == -1) {
                    resultValue = new BigDecimal(0);
                }

                if (resultValue.compareTo(dwydxssrWeightBigDecimal) == 1) {
                    resultValue = dwydxssrWeightBigDecimal;
                }
                sumScore = sumScore.add(resultValue);
                result.put("dwydxssr", resultValue.toString());
            } else {
                result.put("dwydxssr", zeroBigDecimal.toString());
            }
        } else {
            result.put("dwydxssr", new BigDecimal(0).toString());
        }

        //收入利润率
        BigDecimal profitScore = itemData.getScore8();
        PreMuIndexWeightSub profitWeight = preMuIndexWeightMap.get("收入利润率");

        //获取权重
        if (profitWeight != null && profitScore != null) {
            String status = itemData.getStatus();
            BigDecimal profitWeightBigDecimal = profitWeight.getIndexValue() == null ? new BigDecimal(0) : new BigDecimal(profitWeight.getIndexValue());
            BigDecimal profitBaseline = StringUtils.isBlank(profitWeight.getIndexValueLine()) ? new BigDecimal(0) : new BigDecimal(profitWeight.getIndexValueLine());
//            if(!"4".equals(status)){
                BigDecimal rangeDecimal = profitScore.subtract(profitBaseline).abs();
                if(profitScore.compareTo(profitBaseline) == -1){
                    BigDecimal subtractRange = rangeDecimal.divide(profitBaseline, 4, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal("100")).abs();
                    BigDecimal fivePercent = new BigDecimal("5");
                    BigDecimal tenPercent = new BigDecimal("10");
                    BigDecimal twentyPercent = new BigDecimal("20");
                    BigDecimal resultScore = new BigDecimal("0");
                    if (subtractRange.compareTo(fivePercent) <= 0) {
                        // 低于 5%  分值*80%
                        resultScore = profitWeightBigDecimal.multiply(new BigDecimal("0.8"));
                        sumScore = sumScore.add(resultScore);
                        result.put("profit", resultScore.toString());
                    } else if (subtractRange.compareTo(tenPercent) <= 0) {
                        // 5% - 10%  分值*60%
                        resultScore = profitWeightBigDecimal.multiply(new BigDecimal("0.6"));
                        result.put("profit", resultScore.toString());
                        sumScore = sumScore.add(resultScore);
                    } else if (subtractRange.compareTo(twentyPercent) <= 0) {
                        // 10% - 20% 分值*40%
                        resultScore = profitWeightBigDecimal.multiply(new BigDecimal("0.4"));
                        result.put("profit", resultScore.toString());
                        sumScore = sumScore.add(resultScore);
                    } else {
                        // 大于等于 20%  0分
                        result.put("profit", BigDecimal.ZERO.toString());
                    }
                }else{
                    sumScore = sumScore.add(profitWeightBigDecimal);
                    result.put("profit", profitWeightBigDecimal.toString());
                }
//            }else{
//                if (!profitBaseline.equals(BigDecimal.ZERO)) {
//                    sumScore = sumScore.add(profitWeightBigDecimal);
//                    result.put("profit", profitWeightBigDecimal.toString());
//                } else {
//                    result.put("profit", zeroBigDecimal.toString());
//                }
//            }

//            if (!profitBaseline.equals(BigDecimal.ZERO)) {
//                BigDecimal resultValue = profitScore.divide(profitBaseline, 2, BigDecimal.ROUND_HALF_UP).multiply(profitWeightBigDecimal);
//
//                if (resultValue.compareTo(new BigDecimal(0)) == -1) {
//                    resultValue = new BigDecimal(0);
//                }
//
//                if (resultValue.compareTo(profitWeightBigDecimal) == 1) {
//                    resultValue = profitWeightBigDecimal;
//                }
//                sumScore = sumScore.add(resultValue);
//                result.put("profit", resultValue.toString());
//            } else {
//                result.put("profit", zeroBigDecimal.toString());
//            }
        }

        if (StringUtils.equals(itemData.getCompanyType(), "1")) {
//单位能耗销售收入
            BigDecimal dwnhxssr = itemData.getScore2();
            if (dwnhxssr != null && preMuIndexWeightMap.containsKey("单位能耗营业收入")) {
                PreMuIndexWeightSub dwnhxssrWeight = preMuIndexWeightMap.get("单位能耗营业收入");
                BigDecimal dwnhxssrWeightBigDecimal = dwnhxssrWeight.getIndexValue() == null ? new BigDecimal(0) : new BigDecimal(dwnhxssrWeight.getIndexValue());
                BigDecimal dwnhxssrWeightValueLineBigDecimal = dwnhxssrWeight.getIndexValueLine() == null ? new BigDecimal(0) : new BigDecimal(dwnhxssrWeight.getIndexValueLine());
                if (!dwnhxssrWeightValueLineBigDecimal.equals(BigDecimal.ZERO)) {
                    BigDecimal resultValue = dwnhxssr.divide(dwnhxssrWeightValueLineBigDecimal, 2, BigDecimal.ROUND_HALF_UP).multiply(dwnhxssrWeightBigDecimal);

                    if (resultValue.compareTo(new BigDecimal(0)) == -1) {
                        resultValue = new BigDecimal(0);
                    }

                    if (resultValue.compareTo(dwnhxssrWeightBigDecimal) == 1) {
                        resultValue = dwnhxssrWeightBigDecimal;
                    }
                    sumScore = sumScore.add(resultValue);
                    result.put("dwnhxssr", resultValue.toString());
                } else {
                    result.put("dwnhxssr", zeroBigDecimal.toString());
                }
            } else {
                result.put("dwnhxssr", new BigDecimal(0).toString());
            }

            //单位污染物排放销售收入
//      BigDecimal dwwrwpf = mainIncome.divide(totalEquivalent,2,BigDecimal.ROUND_HALF_UP);
            BigDecimal dwwrwpf = itemData.getScore3();
            if (dwwrwpf != null && preMuIndexWeightMap.containsKey("单位污染物排放营业收入")) {
                PreMuIndexWeightSub dwwrwpfxssrWeight = preMuIndexWeightMap.get("单位污染物排放营业收入");
                BigDecimal dwwrwpfxssrWeightBigDecimal = dwwrwpfxssrWeight.getIndexValue() == null ? new BigDecimal(0) : new BigDecimal(dwwrwpfxssrWeight.getIndexValue());
                BigDecimal dwwrwpfxssrWeightValueLineBigDecimal = dwwrwpfxssrWeight.getIndexValueLine() == null ? new BigDecimal(0) : new BigDecimal(dwwrwpfxssrWeight.getIndexValueLine());
                if (!dwwrwpfxssrWeightValueLineBigDecimal.equals(BigDecimal.ZERO)) {
                    BigDecimal resultValue = dwwrwpf.divide(dwwrwpfxssrWeightValueLineBigDecimal, 2, BigDecimal.ROUND_HALF_UP).multiply(dwwrwpfxssrWeightBigDecimal);

                    if (resultValue.compareTo(new BigDecimal(0)) == -1) {
                        resultValue = new BigDecimal(0);
                    }

                    if (resultValue.compareTo(dwwrwpfxssrWeightBigDecimal) == 1) {
                        resultValue = dwwrwpfxssrWeightBigDecimal;
                    }

                    if (StringUtils.isBlank(itemData.getTotalEquivalent()) || Double.parseDouble(itemData.getTotalEquivalent()) == 0) {
                        if (StringUtils.equals(preMuBenefitEvaluation.gethType(), "zero")) {
                            resultValue = BigDecimal.ZERO;
                        } else {
                            resultValue = dwwrwpfxssrWeightBigDecimal;
                        }
                    }

                    sumScore = sumScore.add(resultValue);
                    result.put("dwwrwpfxs", resultValue.toString());
                } else {
                    result.put("dwwrwpfxs", zeroBigDecimal.toString());
                }
            } else {
                result.put("dwwrwpfxs", new BigDecimal(0).toString());
            }


            //研发经费投入强度
//      BigDecimal yfjftrqd = rdFunds.divide(mainIncome,2,BigDecimal.ROUND_HALF_UP);
            BigDecimal yfjftrqd = itemData.getScore4();
            if (yfjftrqd != null && preMuIndexWeightMap.containsKey("研发经费投入强度")) {
                PreMuIndexWeightSub yfjftrqdWeight = preMuIndexWeightMap.get("研发经费投入强度");
                BigDecimal yfjftrqdWeightBigDecimal = yfjftrqdWeight.getIndexValue() == null ? new BigDecimal(0) : new BigDecimal(yfjftrqdWeight.getIndexValue());
                BigDecimal yfjftrqdWeightValueLineBigDecimal = yfjftrqdWeight.getIndexValueLine() == null ? new BigDecimal(0) : new BigDecimal(yfjftrqdWeight.getIndexValueLine());
                if (!yfjftrqdWeightValueLineBigDecimal.equals(BigDecimal.ZERO)) {
                    BigDecimal resultValue = yfjftrqd.divide(yfjftrqdWeightValueLineBigDecimal, 2, BigDecimal.ROUND_HALF_UP).multiply(yfjftrqdWeightBigDecimal);

                    if (resultValue.compareTo(new BigDecimal(0)) == -1) {
                        resultValue = new BigDecimal(0);
                    }

                    if (resultValue.compareTo(yfjftrqdWeightBigDecimal) == 1) {
                        resultValue = yfjftrqdWeightBigDecimal;
                    }
                    sumScore = sumScore.add(resultValue);
                    result.put("yfjftrqd", resultValue.toString());
                } else {
                    result.put("yfjftrqd", zeroBigDecimal.toString());
                }
            } else {
                result.put("yfjftrqd", new BigDecimal(0).toString());
            }


            //全员劳动生产率得分
//      BigDecimal qyldscl = industryOutput.divide(annualEmployees,2,BigDecimal.ROUND_HALF_UP);
            BigDecimal qyldscl = itemData.getScore5();
            if (qyldscl != null && preMuIndexWeightMap.containsKey("全员劳动生产率")) {
                PreMuIndexWeightSub qyldsclWeight = preMuIndexWeightMap.get("全员劳动生产率");
                BigDecimal qyldsclWeightBigDecimal = qyldsclWeight.getIndexValue() == null ? new BigDecimal(0) : new BigDecimal(qyldsclWeight.getIndexValue());
                BigDecimal qyldsclWeightValueLineBigDecimal = qyldsclWeight.getIndexValueLine() == null ? new BigDecimal(0) : new BigDecimal(qyldsclWeight.getIndexValueLine());
                if (!qyldsclWeightValueLineBigDecimal.equals(BigDecimal.ZERO)) {
                    BigDecimal resultValue = qyldscl.divide(qyldsclWeightValueLineBigDecimal, 2, BigDecimal.ROUND_HALF_UP).multiply(qyldsclWeightBigDecimal);

                    if (resultValue.compareTo(new BigDecimal(0)) == -1) {
                        resultValue = new BigDecimal(0);
                    }

                    if (resultValue.compareTo(qyldsclWeightBigDecimal) == 1) {
                        resultValue = qyldsclWeightBigDecimal;
                    }
                    sumScore = sumScore.add(resultValue);
                    result.put("qyldscl", resultValue.toString());
                } else {
                    result.put("qyldscl", zeroBigDecimal.toString());
                }
            } else {
                result.put("qyldscl", new BigDecimal(0).toString());
            }


            //水耗销售收入
//      BigDecimal shxssr = mainIncome.divide(waterBureau,2,BigDecimal.ROUND_HALF_UP);
            BigDecimal shxssr = itemData.getScore6();
            PreMuIndexWeightSub yslWeight = preMuIndexWeightMap.get("单位水耗销售收入");

            //获取权重
            if (yslWeight != null && shxssr != null) {
                BigDecimal ysllWeightBigDecimal = yslWeight.getIndexValue() == null ? new BigDecimal(0) : new BigDecimal(yslWeight.getIndexValue());
                BigDecimal baseline = StringUtils.isBlank(yslWeight.getIndexValueLine()) ? new BigDecimal(0) : new BigDecimal(yslWeight.getIndexValueLine());

                if (!baseline.equals(BigDecimal.ZERO)) {
                    BigDecimal resultValue = shxssr.divide(baseline, 2, BigDecimal.ROUND_HALF_UP).multiply(ysllWeightBigDecimal);

                    if (resultValue.compareTo(new BigDecimal(0)) == -1) {
                        resultValue = new BigDecimal(0);
                    }

                    if (resultValue.compareTo(ysllWeightBigDecimal) == 1) {
                        resultValue = ysllWeightBigDecimal;
                    }
                    sumScore = sumScore.add(resultValue);
                    result.put("ysl", resultValue.toString());
                } else {
                    result.put("ysl", zeroBigDecimal.toString());
                }
            }


        } else {
            result.put("dwwrwpfxs", new BigDecimal(0).toString());
            result.put("yfjftrqd", new BigDecimal(0).toString());
            result.put("ysl", zeroBigDecimal.toString());
            result.put("qyldscl", new BigDecimal(0).toString());
            result.put("dwnhxssr", new BigDecimal(0).toString());
        }


        //计算自定义指标的分值
        BigDecimal customScroe = new BigDecimal(0);
        List<PreMuImportCustomIndexLj> currentCompanyCustomIndexList = companyToCustomIndexMap.get(itemData.getCompanyId());
        if (currentCompanyCustomIndexList != null && !currentCompanyCustomIndexList.isEmpty()) {
            BigDecimal tempIndexSum = BigDecimal.ZERO;
            for (PreMuImportCustomIndexLj temp : currentCompanyCustomIndexList) {
                String indexId = temp.getIndexId();
                //取出原始自定义指标的权重 - 基准值
                PreMuCustomIndicator preMuCustomIndicator = customYsData.get(indexId);
                if (preMuCustomIndicator == null || preMuCustomIndicator.getBaseline() == null || StringUtils.isBlank(preMuCustomIndicator.getIndicatorValues())) {
                    tempIndexSum = tempIndexSum.add(BigDecimal.ZERO);
                } else {
                    String indexValue = temp.getIndexValue();
                    if (StringUtils.isNotBlank(indexValue)) {
                        BigDecimal p = new BigDecimal(indexValue).setScale(2);
                        BigDecimal baseline = preMuCustomIndicator.getBaseline().setScale(2, BigDecimal.ROUND_HALF_UP);
                        BigDecimal weight = new BigDecimal(preMuCustomIndicator.getIndicatorValues()).setScale(2);

                        BigDecimal compnayOnlyIndexBigDecimal = p.divide(baseline, 2, RoundingMode.HALF_UP).multiply(weight);
                        if (compnayOnlyIndexBigDecimal.compareTo(weight) > 0) {
                            compnayOnlyIndexBigDecimal = weight;
                        }
                        tempIndexSum = tempIndexSum.add(compnayOnlyIndexBigDecimal);
                    }
                }
            }
            result.put("quxian", tempIndexSum.setScale(2, BigDecimal.ROUND_HALF_UP).toString());
        }

        //如果该企业存在否决项，那么总分直接0分
        String vetoItemIds = itemData.getVetoItemIds();
        if (StringUtils.isBlank(vetoItemIds)) {
            String quxian = result.get("quxian");
            if (StringUtils.isNotBlank(quxian)) {
                BigDecimal d = new BigDecimal(quxian).setScale(2);
                sumScore = sumScore.add(d);
            }

            //加上加分项分数减去减分项分数
            BigDecimal addScore = itemData.getAddScore() == null ? BigDecimal.ZERO : itemData.getAddScore();
            BigDecimal subScore = itemData.getSubScore() == null ? BigDecimal.ZERO : itemData.getSubScore();
            PreMuIndexWeightSub addSX = preMuIndexWeightMap.get("加减分项");
            if (addSX != null && StringUtils.isNotBlank(addSX.getIndexValue())) {
                BigDecimal cnm = new BigDecimal(addSX.getIndexValue());
                if (addScore.compareTo(cnm) == 1) {
                    sumScore = sumScore.add(cnm);
                } else {
                    sumScore = sumScore.add(addScore);
                }
            } else {
                throw new RuntimeException("没有找到加分项权重");
            }
            sumScore = sumScore.subtract(subScore).setScale(2, RoundingMode.HALF_UP);
            result.put("sum", sumScore.toString());
        } else {
            result.put("sum", zeroBigDecimal.toString());
        }

        return result;
    }

    /**
     * 获取中位数
     */
    private String median(List<BigDecimal> list) {
        if (list.size() == 0) {
            return "0.00";
        }
        Collections.sort(list);
        int size = list.size();
        BigDecimal median;
        if (size % 2 == 1) {
            median = list.get((size - 1) / 2);
        } else {
            median = (list.get(size / 2 - 1).add(list.get(size / 2))).divide(new BigDecimal(2), 3);
        }

        //取两位小数四舍五入
        return median.setScale(2, BigDecimal.ROUND_HALF_UP).toString();
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public int editAll(PreMuBenefitEvaluation preMuBenefitEvaluation) {

        LocalDate localDate = LocalDate.now();
        preMuBenefitEvaluation.setYears(String.valueOf(localDate.getYear() - 1));

        LoginUser loginUser = SecurityUtils.getLoginUser();
        Set<String> roles = loginUser.getRoles();
        if (roles.contains("x_01_011") || roles.contains("along_yellow_river")) {
            String county = loginUser.getSysUser().getDistrict();
            preMuBenefitEvaluation.setCounty(county);
        } else if (roles.contains("s_01_011")) {
            String city = loginUser.getSysUser().getCity();
            preMuBenefitEvaluation.setCity(city);
        }
        List<PreMuBenefitEvaluation> list = preMuBenefitEvaluationMapper.selectPreMuBenefitEvaluationHsList(preMuBenefitEvaluation);

        int collectSize = 0;
        List<PreMuBenefitEvaluation> dbList = new ArrayList<>();
        for (PreMuBenefitEvaluation temp : list) {
            temp.setStatus("1");
            dbList.add(temp);

            if (dbList.size() > 100) {
                preMuBenefitEvaluationMapper.updateBatch(dbList);
                collectSize += dbList.size();
                dbList.clear();
            }
        }
        if (!dbList.isEmpty()) {
            preMuBenefitEvaluationMapper.updateBatch(dbList);
            collectSize += dbList.size();
            dbList.clear();
        }
        return collectSize;

//        if(list != null && !list.isEmpty()){
//            List<PreMuBenefitEvaluation> collect = list.stream().map(a -> {
//                a.setStatus("1");
//                return a;
//            }).collect(Collectors.toList());
//            preMuBenefitEvaluationMapper.updateBatch(list);
//            return collect.size();
//        }else {
//            return  0;
//        }
    }

    @Override
    public List<PreMuBenefitEvaluationVo> getExportList(PreMuBenefitEvaluation preMuBenefitEvaluation) {
        return preMuBenefitEvaluationMapper.getExportList(preMuBenefitEvaluation);
    }

    @Override
    public List<PreMuBenefitEvaluation20250520Vo> getExportList2025(PreMuBenefitEvaluation preMuBenefitEvaluation) {
        return preMuBenefitEvaluationMapper2025.getExportList(preMuBenefitEvaluation);
    }

    @Override
    public List<PreMuIndustryBenefitEvaluationVo> getExportListGroupIndustry(PreMuBenefitEvaluation preMuBenefitEvaluation) {
        return preMuBenefitEvaluationMapper.getExportListGroupIndustry(preMuBenefitEvaluation);
    }

    @Override
    public List<PreMuIndustryBenefitEvaluationVo20250520> getExportListGroupIndustry2025(PreMuBenefitEvaluation preMuBenefitEvaluation) {
        return preMuBenefitEvaluationMapper2025.getExportListGroupIndustry2025(preMuBenefitEvaluation);
    }

    @Override
    public List<PreMuLevelBenefitEvaluationVo> getExportListGroupLevel(PreMuBenefitEvaluation preMuBenefitEvaluation) {
        return preMuBenefitEvaluationMapper.getExportListGroupLevel(preMuBenefitEvaluation);
    }

    @Override
    public List<PreMuLevelBenefitEvaluationVo20250520> getExportListGroupLevel2025(PreMuBenefitEvaluation preMuBenefitEvaluation){
        return preMuBenefitEvaluationMapper2025.getExportListGroupLevel2025(preMuBenefitEvaluation);
    }


    @Override
    public PreMuScheduleManagementVo groupArea(PreMuBenefitEvaluation preMuBenefitEvaluation) {

        return preMuBenefitEvaluationMapper.groupArea(preMuBenefitEvaluation);
    }

    @Override
    public List<PreMuBenefitEvaluation> getVillageCount(String countyCode) {
        return preMuBenefitEvaluationMapper.getVillageCount(countyCode);
    }

    @Override
    public List<PreMuBenefitEvaluation> getCountyCount(String cityCode) {

        return preMuBenefitEvaluationMapper.getCountyCount(cityCode);
    }

    @Override
    public List<PreMuChartsVo> getPj(PreMuAreaTreeDto areaTreeDto) {

        return preMuBenefitEvaluationMapper.getPj(areaTreeDto);
    }

    @Override
    public List<PreMuChartsVo> groupDimensionLevel(PreMuChartsDto preMuChartsDto) {

        return preMuBenefitEvaluationMapper.groupDimensionLevel(preMuChartsDto);
    }

    @Override
    public List<PreMuChartsVo> groupProportionLevel(PreMuChartsDto preMuChartsDto) {

        return preMuBenefitEvaluationMapper.groupProportionLevel(preMuChartsDto);
    }

    @Override
    public List<PreMuChartsVo> groupDimensionArea(PreMuChartsDto preMuChartsDto) {

        return preMuBenefitEvaluationMapper.groupDimensionArea(preMuChartsDto);
    }

    @Override
    public List<PreMuChartsVo> groupIndexByCity(PreMuChartsDto preMuChartsDto) {

        return preMuBenefitEvaluationMapper.groupIndexByCity(preMuChartsDto);
    }

    @Override
    public PreMuChartsVo getAvgNum(PreMuChartsDto preMuChartsDto) {
        return preMuBenefitEvaluationMapper.getAvgNum(preMuChartsDto);
    }

    @Override
    public List<PreMuChartsVo> groupIndexByIndustry(PreMuChartsDto preMuChartsDto) {

        return preMuBenefitEvaluationMapper.groupIndexByIndustry(preMuChartsDto);
    }

    @Override
    public List<PreMuChartsVo> groupAreaIndustry(PreMuChartsDto preMuChartsDto) {

        return preMuBenefitEvaluationMapper.groupAreaIndustry(preMuChartsDto);
    }

    @Override
    public List<PreMuChartsVo> groupCompanyByIndustry(PreMuChartsDto preMuChartsDto) {

        return preMuBenefitEvaluationMapper.groupCompanyByIndustry(preMuChartsDto);
    }

    @Override
    public List<PreMuChartsVo> groupByArea(PreMuChartsDto preMuChartsDto) {

        return preMuBenefitEvaluationMapper.groupByArea(preMuChartsDto);
    }

    @Override
    public List<PreMuChartsVo> groupByAreaIndustry(PreMuChartsDto preMuChartsDto) {
        return preMuBenefitEvaluationMapper.groupByAreaIndustry(preMuChartsDto);
    }

    @Override
    public List<PreMuChartsVo> groupEconomyByYears(PreMuChartsDto preMuChartsDto) {

        return preMuBenefitEvaluationMapper.groupEconomyByYears(preMuChartsDto);
    }

    @Override
    public List<PreMuChartsVo> economyGruopArea(PreMuChartsDto preMuChartsDto) {

        return preMuBenefitEvaluationMapper.economyGruopArea(preMuChartsDto);
    }

    @Override
    public List<PreMuChartsVo> economyGruopIndustry(PreMuChartsDto preMuChartsDto) {

        return preMuBenefitEvaluationMapper.economyGruopIndustry(preMuChartsDto);
    }

    @Override
    public PreMuGradingRatioVo getGradingRatioVo(PreMuBenefitEvaluation preMuBenefitEvaluation) {

        LoginUser loginUser = SecurityUtils.getLoginUser();
        Set<String> roles = loginUser.getRoles();
        if (roles.contains("x_01_011") || roles.contains("along_yellow_river")) {
            String county = loginUser.getSysUser().getDistrict();
            preMuBenefitEvaluation.setCounty(county);
        } else if (roles.contains("s_01_011")) {
            String city = loginUser.getSysUser().getCity();
            preMuBenefitEvaluation.setCity(city);
        } else if (roles.contains("p_01_011")) {
            String province = loginUser.getSysUser().getProvince();
            preMuBenefitEvaluation.setProvince(province);
        }

        return preMuBenefitEvaluationMapper.getGradingRatioVo(preMuBenefitEvaluation);
    }

    @Override
    public void updateStatusByIds(List<String> idList) {
        preMuBenefitEvaluationMapper.updateStatusByIds(idList);
    }

    @Override
    public void updateVerifyByIds(List<String> idList) {
        preMuBenefitEvaluationMapper.updateVerifyByIds(idList);
    }

    /**
     * <p>
     * 试算应用
     * </p>
     *
     * @param params
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public AjaxResult adhibition(PreMuBenefitEvaluationDto params) {

        int diffrentCalTypeCount = preMuBenefitEvaluationMapper.selectDiffrentCalTypeCount(params);
        if(diffrentCalTypeCount > 0){
            return AjaxResult.warn("您已进行试算评价，为避免数据冲突，暂无法同时进行其他类型试算。");
        }

        /**
         * 查询出当前区县中待试算的数据
         */
        if ("-1".equals(params.getIndustry())) {
            PreMuIndexWeightMain preMuIndexWeightMain = new PreMuIndexWeightMain();
            preMuIndexWeightMain.setCompanyType(params.getCompanyType());
            preMuIndexWeightMain.setCounty(params.getCounty());
            preMuIndexWeightMain.setYear(params.getYears());

            List<PreMuIndexWeightMain> preMuIndexWeightMains = preMuIndexWeightMainMapper.selectPreMuIndexWeightMainListNew(preMuIndexWeightMain);

            if (!CollectionUtils.isEmpty(preMuIndexWeightMains)) {
                List<String> industries = preMuIndexWeightMains.stream()
                        .map(PreMuIndexWeightMain::getIndustry)
                        .filter(industry -> !StringUtils.isEmpty(industry) && !"-1".equals(industry)) // 更新的过滤条件
                        .collect(Collectors.toList());

                if (!CollectionUtils.isEmpty(industries)) {
                    List<String> industryCodeList = new ArrayList<>();
                    for (String industryCode : industries) {
                        String[] codes = industryCode.split(",");
                        industryCodeList.addAll(Arrays.asList(codes));
                    }

                    params.setExcludeIndustryList(industryCodeList);
                }
            }
        }
        params.setExcludeCalculateTypeFlag(true);
        List<PreMuBenefitEvaluation> dataList = preMuBenefitEvaluationMapper.selectPreMuBenefitEvaluationList(params);

        if (dataList == null || dataList.isEmpty()) {
            return AjaxResult.warn("没有找到要试算的数据");
        }
        long numberOfUnverifiedEnterprises = dataList.stream().filter(i -> StringUtils.equals(i.getStatus(), "0")).count();
        if (numberOfUnverifiedEnterprises > 0L) {
            return AjaxResult.warn("您有企业未核实,请您先通知企业核实!");
        }

        //计算需要权重和基准值，查询基准值和权重
        //1.查询指标管理中的权重和基准值
        PreMuIndexWeightMain preMuIndexWeightMainQueryParams = new PreMuIndexWeightMain();
        preMuIndexWeightMainQueryParams.setYear(params.getYears());
        preMuIndexWeightMainQueryParams.setCompanyType(params.getCompanyType());
        preMuIndexWeightMainQueryParams.setCounty(params.getCounty());
        preMuIndexWeightMainQueryParams.setPark(params.getPark());
        preMuIndexWeightMainQueryParams.setIndustry(params.getIndustry());
        PreMuIndexWeightMain preMuIndexWeightMain = preMuIndexWeightMainMapper.selectOne(preMuIndexWeightMainQueryParams);

        if (preMuIndexWeightMain == null || preMuIndexWeightMain.getPreMuIndexWeightSubList() == null || preMuIndexWeightMain.getPreMuIndexWeightSubList().isEmpty()) {
            StringBuilder sb = new StringBuilder(String.format("%s年当前区县没有设置", params.getYears()));
            if(!StringUtils.isEmpty(params.getCompanyType())){
                String enterType = StringUtils.equals(params.getCompanyType(), "2") ? "规下企业" : "规上企业";
                sb.append(enterType);
            }
            if(!StringUtils.isEmpty(params.getIndustry())){
                sb.append(params.getIndustry());
            }
            if(!StringUtils.isEmpty(params.getPark())){
                sb.append(params.getPark());
            }
            sb.append("自定义指标");
            throw new RuntimeException(sb.toString());
        }


        String park = params.getPark();
        String industry = params.getIndustry();
        if(StringUtils.isEmpty(park) && StringUtils.isEmpty(industry)){
            params.setCalculateType("00");
        } else if (StringUtils.isEmpty(park)) {
            params.setCalculateType("01");
        }else if (StringUtils.isEmpty(industry)) {
            params.setCalculateType("02");
        }else{
            return AjaxResult.warn("不允许同时选园区和行业");
        }

        //取出待试算企业的ID
        List<String> dssCompanyIds = dataList.stream().map(PreMuBenefitEvaluation::getCompanyId).collect(Collectors.toList());
        List<String> ids = dataList.stream().map(PreMuBenefitEvaluation::getId).collect(Collectors.toList());


        //查询企业的自定义指标值,通过待试算的企业ID
        List<PreMuImportCustomIndexLj> companyCustomIndexValueList = preMuImportCustomIndexLjMapper.selectPreMuimportCustomIndexLjListByCompanyId(dssCompanyIds);
        //企业ID对应的自定义指标值
        Map<String, List<PreMuImportCustomIndexLj>> companyToCustomIndexMap = new HashMap<>();
        if (companyCustomIndexValueList != null && !companyCustomIndexValueList.isEmpty()) {
            companyToCustomIndexMap = companyCustomIndexValueList.stream().collect(Collectors.groupingBy(PreMuImportCustomIndexLj::getEnterId));
        }

        //查询自定义指标的信息，当前年度、当前区县、当前企业类型
        PreMuCustomIndicator queryParams = new PreMuCustomIndicator();
        queryParams.setYear(params.getYears());
        queryParams.setCounty(params.getCounty());
        queryParams.setCompanyType(params.getCompanyType());
        List<PreMuCustomIndicator> preMuCustomIndicators = preMuCustomIndicatorMapper.selectPreMuCustomIndicatorList(queryParams);

        Map<String, PreMuCustomIndicator> customYsData = new HashMap<>();

        if (preMuCustomIndicators != null && !preMuCustomIndicators.isEmpty()) {
            customYsData = preMuCustomIndicators.stream().collect(Collectors.toMap(PreMuCustomIndicator::getId, v -> v));
        }

        //如果指标管理中的指标有数据，则将指标获取出来存到Map中
        /**
         * Key：指标名称，value:指标值
         */
        Map<String, PreMuIndexWeightSub> preMuIndexWeightMap = new HashMap<>(16);
        if (preMuIndexWeightMain != null && preMuIndexWeightMain.getPreMuIndexWeightSubList() != null && !preMuIndexWeightMain.getPreMuIndexWeightSubList().isEmpty()) {
            List<PreMuIndexWeightSub> preMuIndexWeightSubList = preMuIndexWeightMain.getPreMuIndexWeightSubList();
            preMuIndexWeightMap = preMuIndexWeightSubList.stream().collect(Collectors.toMap(PreMuIndexWeightSub::getIndexName, v -> v));
        }

        BigDecimal zeroBigDecimal = new BigDecimal(0);

        List<PreMuBenefitEvaluation> updateList = new ArrayList<>();

        //遍历待试算的数据
        for (PreMuBenefitEvaluation itemData : dataList) {
            String id = itemData.getId();
            Map<String, String> result = calculateScores(params, companyToCustomIndexMap, customYsData, preMuIndexWeightMap, zeroBigDecimal, itemData);
            PreMuBenefitEvaluation updateMe = new PreMuBenefitEvaluation();
            updateMe.setId(id);
            updateMe.setCalculateType(params.getCalculateType());

            //原来逻辑存在问题，在应用的时候只需要更新总分就可以了，不用更新score1等值

//            BigDecimal dwydssBigDecimal = StringUtils.isBlank(result.get("dwydss")) ? null : new BigDecimal(result.get("dwydss"));
//            updateMe.setScore1(dwydssBigDecimal);
//
//            BigDecimal dwnhxssrBigDecimal = StringUtils.isBlank(result.get("dwnhxssr")) ? null : new BigDecimal(result.get("dwnhxssr"));
//            updateMe.setScore2(dwnhxssrBigDecimal);
//
//            BigDecimal dwwrwpfxsBigDecimal = StringUtils.isBlank(result.get("dwwrwpfxs")) ? null : new BigDecimal(result.get("dwwrwpfxs"));
//            updateMe.setScore3(dwwrwpfxsBigDecimal);
//
//            BigDecimal yfjftrqdBigDecimal = StringUtils.isBlank(result.get("yfjftrqd")) ? null : new BigDecimal(result.get("yfjftrqd"));
//            updateMe.setScore4(yfjftrqdBigDecimal);
//
//            BigDecimal qyldsclBigDecimal = StringUtils.isBlank(result.get("qyldscl")) ? null : new BigDecimal(result.get("qyldscl"));
//            updateMe.setScore5(qyldsclBigDecimal);
//
//            BigDecimal yslBigDecimal = StringUtils.isBlank(result.get("ysl")) ? null : new BigDecimal(result.get("ysl"));
//            updateMe.setScore6(yslBigDecimal);
//
//            BigDecimal dwydxssrBigDecimal = StringUtils.isBlank(result.get("dwydxssr")) ? null : new BigDecimal(result.get("dwydxssr"));
//            updateMe.setScore7(dwydxssrBigDecimal);

            BigDecimal sumBigDecimal = StringUtils.isBlank(result.get("sum")) ? null : new BigDecimal(result.get("sum"));
            updateMe.setSumScore(sumBigDecimal);

            updateList.add(updateMe);

            if (updateList.size() > 100) {
                preMuBenefitEvaluationMapper.updateBatchNew(updateList);
                updateList.clear();
            }
        }
        if (!updateList.isEmpty()) {
            preMuBenefitEvaluationMapper.updateBatchNew(updateList);
            updateList.clear();
        }

        //修改数据的状态为待评级
        preMuBenefitEvaluationMapper.updateStatusDpjByIds(ids);
        return AjaxResult.success();
    }

    /**
     * <p>
     * 一键评级
     * </p>
     *
     * @param year        年份
     * @param companyType 企业类型
     * @param district    区县
     * @param park    园区
     * @param industryType    工业
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public AjaxResult evaluate(String year, String companyType, String district, String park, String industryType) {

        String ratingMark = "0";

        //判断是否有未核实的数据
        PreMuBenefitEvaluation queryNoCheckDataParams = new PreMuBenefitEvaluation();
        queryNoCheckDataParams.setYears(year);
        queryNoCheckDataParams.setCompanyType(companyType);
        queryNoCheckDataParams.setCounty(district);
        queryNoCheckDataParams.setStatus("0");
        PreMuBenefitEvaluationDto dto = new PreMuBenefitEvaluationDto();
        BeanUtil.copyProperties(queryNoCheckDataParams, dto );
        //查询表中没有核实的数据
        List<PreMuBenefitEvaluation> preMuBenefitEvaluations = preMuBenefitEvaluationMapper.selectPreMuBenefitEvaluationList(dto);
        if (preMuBenefitEvaluations != null && !preMuBenefitEvaluations.isEmpty()) {
            long count = preMuBenefitEvaluations.stream().count();
            if (count > 0L) {
                return AjaxResult.warn(String.format("尚有企业未核实数据%s条，请所有企业核实完再评级", count));
            }
        }
        queryNoCheckDataParams.setStatus(null);
        //查询表中没有试算的数据
        List<PreMuBenefitEvaluation> noTrialCompanyList = preMuBenefitEvaluationMapper.selectPreMuBenefitEvaluationListBySumScoreIsNull(queryNoCheckDataParams, "1");
        if (noTrialCompanyList != null && !noTrialCompanyList.isEmpty()) {
            long count = noTrialCompanyList.stream().count();
            if (count > 0L) {
                return AjaxResult.warn(String.format("尚有数据%s条,未试算请先试算!", count));
            }
        }


        List<PreMuJszxHy> industryList = preMuCompanyInfoMapper.getJszx_hy();


        //查询评级的比例数据
        PreMuRate rateQueryParams = new PreMuRate();
        rateQueryParams.setYears(year);
        rateQueryParams.setDistrictCode(district);
        List<PreMuRate> preMuRates = preMuRateMapper.selectPreMuRateList(rateQueryParams);

        BigDecimal aRatio = null;
        BigDecimal bRatio = null;
        BigDecimal cRatio = null;
        BigDecimal dRatio = null;
        if (preMuRates != null && !preMuRates.isEmpty()) {
            PreMuRate preMuRate = preMuRates.get(0);
            aRatio = preMuRate.getRateA() == null ? new BigDecimal(0) : new BigDecimal(preMuRate.getRateA());
            bRatio = preMuRate.getRateB() == null ? new BigDecimal(0) : new BigDecimal(preMuRate.getRateB());
            cRatio = preMuRate.getRateC() == null ? new BigDecimal(0) : new BigDecimal(preMuRate.getRateC());
            dRatio = preMuRate.getRateD() == null ? new BigDecimal(0) : new BigDecimal(preMuRate.getRateD());

            if (aRatio.compareTo(BigDecimal.ZERO) == 0
                    || bRatio.compareTo(BigDecimal.ZERO) == 0
                    || cRatio.compareTo(BigDecimal.ZERO) == 0
                    || dRatio.compareTo(BigDecimal.ZERO) == 0) {
                return AjaxResult.warn("评级的比例中出现了为0的数据，请核查比例数据！");
            }
        } else {
            return AjaxResult.warn("请先维护评级的比例数据！");
        }

        PreMuBenefitEvaluationDto queryParams = new PreMuBenefitEvaluationDto();
        queryParams.setYears(year);
        queryParams.setCounty(district);
        queryParams.setCompanyType(companyType);
        queryParams.setPark(park);
        queryParams.setIndustryType(industryType);
        List<String> excludeIndustryCodeList = new ArrayList<>();
        if ("-1".equals(industryType)) {
            PreMuIndexWeightMain preMuIndexWeightMain = new PreMuIndexWeightMain();
            preMuIndexWeightMain.setCompanyType(companyType);
            preMuIndexWeightMain.setCounty(district);
            preMuIndexWeightMain.setYear(year);


            List<PreMuIndexWeightMain> preMuIndexWeightMains = preMuIndexWeightMainMapper.selectPreMuIndexWeightMainListNew(preMuIndexWeightMain);

            if (!CollectionUtils.isEmpty(preMuIndexWeightMains)) {
                List<String> industries = preMuIndexWeightMains.stream()
                        .map(PreMuIndexWeightMain::getIndustry)
                        .filter(industry -> !StringUtils.isEmpty(industry) && !"-1".equals(industry))
                        .collect(Collectors.toList());

                if (!CollectionUtils.isEmpty(industries)) {

                    for (String industryCode : industries) {
                        String[] codes = industryCode.split(",");
                        excludeIndustryCodeList.addAll(Arrays.asList(codes));
                    }

                    queryParams.setExcludeIndustryList(excludeIndustryCodeList);
                }
            }
        }
        int count = preMuBenefitEvaluationMapper.count(queryParams);
        if (count == 0) {
            return AjaxResult.warn("没有找到需要评级的数据");
        }
        int aCount = (int) Math.floor(count * (aRatio.doubleValue() / 100));
        int dCount = (int) Math.ceil(count * (dRatio.doubleValue() / 100));
        int cCount = (int) Math.floor(count * (cRatio.doubleValue() / 100));
        int bCount = count - aCount - dCount - cCount;

        List<String> idList = new ArrayList<>();
        Map<String, Object> paramMap = new HashMap<String, Object>();
//        if (aCount > 0) {
//            paramMap = new HashMap<String, Object>();
//            paramMap.put("year", year);
//            paramMap.put("county", district);
//            paramMap.put("companyType", companyType);
//            paramMap.put("park",park);
//            paramMap.put("industryType",industryType);
//            paramMap.put("startNum", 0);
//            paramMap.put("count", aCount);
//            if("-1".equals(industryType)) {
//                paramMap.put("excludeIndustryList", excludeIndustryCodeList);
//            }
//            idList = preMuBenefitEvaluationMapper.getIdsBySumScore(paramMap);
//            if (!idList.isEmpty()) {
//                preMuBenefitEvaluationMapper.updateMjLevelByIds(idList, "A", ratingMark);
//            }
//        }
//
//        if (bCount > 0) {
//            paramMap = new HashMap<String, Object>();
//            paramMap.put("year", year);
//            paramMap.put("county", district);
//            paramMap.put("companyType", companyType);
//            paramMap.put("park",park);
//            paramMap.put("industryType",industryType);
//            paramMap.put("startNum", aCount);
//            paramMap.put("count", bCount);
//            if("-1".equals(industryType)) {
//                paramMap.put("excludeIndustryList", excludeIndustryCodeList);
//            }
//            idList = preMuBenefitEvaluationMapper.getIdsBySumScore(paramMap);
//            if (!idList.isEmpty()) {
//                preMuBenefitEvaluationMapper.updateMjLevelByIds(idList, "B", ratingMark);
//            }
//        }
//        if (cCount > 0) {
//            paramMap = new HashMap<String, Object>();
//            paramMap.put("year", year);
//            paramMap.put("county", district);
//            paramMap.put("companyType", companyType);
//            paramMap.put("park",park);
//            paramMap.put("industryType",industryType);
//            paramMap.put("startNum", aCount + bCount);
//            paramMap.put("count", cCount);
//            if("-1".equals(industryType)) {
//                paramMap.put("excludeIndustryList", excludeIndustryCodeList);
//            }
//            idList = preMuBenefitEvaluationMapper.getIdsBySumScore(paramMap);
//            if (!idList.isEmpty()) {
//                preMuBenefitEvaluationMapper.updateMjLevelByIds(idList, "C", ratingMark);
//            }
//        }
//
//        if (dCount > 0) {
//            paramMap = new HashMap<String, Object>();
//            paramMap.put("year", year);
//            paramMap.put("county", district);
//            paramMap.put("companyType", companyType);
//            paramMap.put("park",park);
//            paramMap.put("industryType",industryType);
//            paramMap.put("startNum", aCount + bCount + cCount);
//            paramMap.put("count", dCount);
//            if("-1".equals(industryType)) {
//                paramMap.put("excludeIndustryList", excludeIndustryCodeList);
//            }
//            idList = preMuBenefitEvaluationMapper.getIdsBySumScore(paramMap);
//            if (!idList.isEmpty()) {
//                preMuBenefitEvaluationMapper.updateMjLevelByIds(idList, "D", ratingMark);
//            }
//        }

        paramMap.put("year", year);
        paramMap.put("county", district);
        paramMap.put("companyType", companyType);
        paramMap.put("park", park);
        paramMap.put("industryType", industryType);
        if ("-1".equals(industryType)) {
            paramMap.put("excludeIndustryList", excludeIndustryCodeList);
        }

        List<String> allIdList = preMuBenefitEvaluationMapper.getAllIdsSortedBySumScore(paramMap);

        if (allIdList.isEmpty()) {
            return AjaxResult.warn("没有找到需要评级的数据");
        }

        int startA = 0;
        int endA = aCount;

        int startB = endA;
        int endB = startB + bCount;

        int startC = endB;
        int endC = startC + cCount;

        int startD = endC;
        int endD = startD + dCount;

// 使用 subList 截取（注意边界判断）
        List<String> aList = safeSubList(allIdList, startA, endA);
        List<String> bList = safeSubList(allIdList, startB, endB);
        List<String> cList = safeSubList(allIdList, startC, endC);
        List<String> dList = safeSubList(allIdList, startD, endD);

// 更新等级
        if (!aList.isEmpty()) {
            preMuBenefitEvaluationMapper.updateMjLevelByIds(aList, "A", ratingMark);
        }
        if (!bList.isEmpty()) {
            preMuBenefitEvaluationMapper.updateMjLevelByIds(bList, "B", ratingMark);
        }
        if (!cList.isEmpty()) {
            preMuBenefitEvaluationMapper.updateMjLevelByIds(cList, "C", ratingMark);
        }
        if (!dList.isEmpty()) {
            preMuBenefitEvaluationMapper.updateMjLevelByIds(dList, "D", ratingMark);
        }


        //查询出所有得分为0的 设置为D类
        paramMap = new HashMap<String, Object>();
        paramMap.put("year", year);
        paramMap.put("county", district);
        paramMap.put("park",park);
        paramMap.put("industryType",industryType);
        paramMap.put("companyType", companyType);
        if("-1".equals(industryType)) {
            paramMap.put("excludeIndustryList", excludeIndustryCodeList);
        }
        idList = preMuBenefitEvaluationMapper.selectCurrentCoutnySorceEqZero(paramMap);
        if (idList != null && !idList.isEmpty()) {
            preMuBenefitEvaluationMapper.updateMjLevelByIds(idList, "D", ratingMark);
        }

//        for (int i = 0; i < industryList.size(); i++) {
//            PreMuJszxHy preMuJszxHy = industryList.get(i);
//            String industryType = preMuJszxHy.getDL();
//            PreMuBenefitEvaluation queryParams = new PreMuBenefitEvaluation();
//            queryParams.setYears(year);
//            queryParams.setCounty(district);
//            queryParams.setIndustryType(industryType);
//            queryParams.setCompanyType(companyType);
//            int count = preMuBenefitEvaluationMapper.count(queryParams);
//            if (count == 0) {
//                continue;
//            }
//            int aCount = (int) Math.floor(count * aRatio.doubleValue() / 100);
//            int dCount = (int) Math.ceil(count * dRatio.doubleValue() / 100);
//            int cCount = (int) Math.floor(count * cRatio.doubleValue() / 100);
//            int bCount = count - aCount - dCount - cCount;
//
//            List<String> idList = new ArrayList<>();
//            Map<String,Object> paramMap = new HashMap<String, Object>();
//            if (aCount > 0) {
//                paramMap = new HashMap<String, Object>();
//                paramMap.put("year", year);
//                paramMap.put("county", district);
//                paramMap.put("industryType", industryType);
//                paramMap.put("companyType", companyType);
//                paramMap.put("startNum", 0);
//                paramMap.put("count", aCount);
//                idList = preMuBenefitEvaluationMapper.getIdsBySumScore(paramMap);
//                preMuBenefitEvaluationMapper.updateMjLevelByIds(idList, "A", ratingMark);
//            }
//
//            if (bCount > 0) {
//                paramMap = new HashMap<String, Object>();
//                paramMap.put("year", year);
//                paramMap.put("county", district);
//                paramMap.put("companyType", companyType);
//                paramMap.put("industryType", industryType);
//                paramMap.put("startNum", aCount);
//                paramMap.put("count", bCount);
//                idList = preMuBenefitEvaluationMapper.getIdsBySumScore(paramMap);
//                preMuBenefitEvaluationMapper.updateMjLevelByIds(idList, "B", ratingMark);
//            }
//            if (cCount > 0) {
//                paramMap = new HashMap<String, Object>();
//                paramMap.put("year", year);
//                paramMap.put("county", district);
//                paramMap.put("industryType", industryType);
//                paramMap.put("companyType", companyType);
//                paramMap.put("startNum", aCount + bCount);
//                paramMap.put("count", cCount);
//                idList = preMuBenefitEvaluationMapper.getIdsBySumScore(paramMap);
//                preMuBenefitEvaluationMapper.updateMjLevelByIds(idList, "C", ratingMark);
//            }
//
//            if (dCount > 0) {
//                paramMap = new HashMap<String, Object>();
//                paramMap.put("year", year);
//                paramMap.put("county", district);
//                paramMap.put("industryType", industryType);
//                paramMap.put("companyType", companyType);
//                paramMap.put("startNum", aCount + bCount + cCount);
//                paramMap.put("count", dCount);
//                idList = preMuBenefitEvaluationMapper.getIdsBySumScore(paramMap);
//                preMuBenefitEvaluationMapper.updateMjLevelByIds(idList, "D", ratingMark);
//            }
//        }
        return AjaxResult.success();
    }

    /**
     * 取消评级
     *
     * @param chartsDto
     */
    @Override
    public AjaxResult grade(PreMuChartsDto chartsDto) {

        //设置取消评级的年份
        LocalDate localDate = LocalDate.now();
        chartsDto.setYears(String.valueOf(localDate.getYear() - 1));
        if ("-1".equals(chartsDto.getIndustry())) {
            PreMuIndexWeightMain preMuIndexWeightMain = new PreMuIndexWeightMain();
            preMuIndexWeightMain.setCompanyType(chartsDto.getCompanyType());
            preMuIndexWeightMain.setCounty(chartsDto.getCounty());
            preMuIndexWeightMain.setYear(chartsDto.getYears());

            List<PreMuIndexWeightMain> preMuIndexWeightMains = preMuIndexWeightMainMapper.selectPreMuIndexWeightMainListNew(preMuIndexWeightMain);

            if (!CollectionUtils.isEmpty(preMuIndexWeightMains)) {
                List<String> industries = preMuIndexWeightMains.stream()
                        .map(PreMuIndexWeightMain::getIndustry)
                        .filter(industry -> !StringUtils.isEmpty(industry) && !"-1".equals(industry)) // 更新的过滤条件
                        .collect(Collectors.toList());

                if (!CollectionUtils.isEmpty(industries)) {
                    List<String> industryCodeList = new ArrayList<>();
                    for (String industryCode : industries) {
                        String[] codes = industryCode.split(",");
                        industryCodeList.addAll(Arrays.asList(codes));
                    }

                    chartsDto.setExcludeIndustryList(industryCodeList);
                }
            }
        }
        //查询当前年度县中的企业，通过企业类型筛选
        List<PreMuBenefitEvaluation> totaList = preMuBenefitEvaluationMapper.getTotal(chartsDto);

        //退回不参评的企业状态
        PreMuImportBenefitEvaluationNo preMuImportBenefitEvaluationNo = new PreMuImportBenefitEvaluationNo();
        preMuImportBenefitEvaluationNo.setYear(Long.valueOf(chartsDto.getYears()));
        preMuImportBenefitEvaluationNo.setCompanyType(chartsDto.getCompanyType());
        preMuImportBenefitEvaluationNo.setCounty(SecurityUtils.getLoginUser().getSysUser().getDistrict());
        List<PreMuImportBenefitEvaluationNo> preMuImportBenefitEvaluationNos = preMuImportBenefitEvaluationNoMapper.listEvaNO(preMuImportBenefitEvaluationNo);

        if (preMuImportBenefitEvaluationNos != null && !preMuImportBenefitEvaluationNos.isEmpty()) {
            List<String> noBenefitEvaluationIds = preMuImportBenefitEvaluationNos.stream().map(PreMuImportBenefitEvaluationNo::getId).collect(Collectors.toList());
            preMuImportBenefitEvaluationNoMapper.updateNoEvaluationCancelStatusById(noBenefitEvaluationIds);
        }

        List<String> list = new ArrayList<>();

        for (int i = 0; i < totaList.size(); i++) {
            PreMuBenefitEvaluation mcBenefitEvaluationDO = totaList.get(i);
            if (mcBenefitEvaluationDO.getStatus().equals("0")) {
                return AjaxResult.warn("数据未核实，不可取消评级");
            }
            if (mcBenefitEvaluationDO.getStatus().equals("1")) {
                return AjaxResult.warn("数据未评级，不可取消评级");
            }
            if (mcBenefitEvaluationDO.getStatus().equals("2")) {
                return AjaxResult.warn("数据已驳回，不可取消评级");
            }
            if (mcBenefitEvaluationDO.getStatus().equals("3")) {
                return AjaxResult.warn("数据未评级，不可取消评级");
            }
            if (mcBenefitEvaluationDO.getStatus().equals("5")) {
                return AjaxResult.warn("数据封存，不可取消评级");
            }
            list.add(mcBenefitEvaluationDO.getId());
            if (list.size() > 100) {
                preMuBenefitEvaluationMapper.cleanLevel(list);
                list.clear();
            }
        }
        if (!list.isEmpty()) {
            preMuBenefitEvaluationMapper.cleanLevel(list);
            list.clear();
        }
        return AjaxResult.success();
    }

    /**
     * 升档降档
     *
     * @param params
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public AjaxResult changeLevel(Map<String, String> params) {

        /**
         * id:数据的ID，willLevel:是升档还是降档
         */
        String id = "", willLevel = "", ly = "";
        if (StringUtils.isBlank(id = params.get("id")) || StringUtils.isBlank(willLevel = params.get("willLevel")) || StringUtils.isBlank(ly = params.get("ly"))) {
            return AjaxResult.warn("请选择要升档/降档的数据或升档/降档理由");
        }
        PreMuBenefitEvaluation preMuBenefitEvaluation = preMuBenefitEvaluationMapper.selectPreMuBenefitEvaluationById(id);


        //升档
        if (StringUtils.equals(willLevel, "1")) {
            preMuBenefitEvaluation.setUpgradeIds(ly);
            if (StringUtils.equals(preMuBenefitEvaluation.getMjLevel(), "A")) {
                return AjaxResult.warn(String.format("升档失败,企业【%s】已是最高档", preMuBenefitEvaluation.getCompanyName()));
            } else if (StringUtils.equals(preMuBenefitEvaluation.getMjLevel(), "B")) {
                preMuBenefitEvaluation.setMjLevel("A");
                upLevel(preMuBenefitEvaluation, ly, willLevel);
            } else if (StringUtils.equals(preMuBenefitEvaluation.getMjLevel(), "C")) {
                preMuBenefitEvaluation.setMjLevel("B");
                upLevel(preMuBenefitEvaluation, ly, willLevel);
            } else if (StringUtils.equals(preMuBenefitEvaluation.getMjLevel(), "D")) {
                preMuBenefitEvaluation.setMjLevel("C");
                upLevel(preMuBenefitEvaluation, ly, willLevel);
            }
        } else if (StringUtils.equals(willLevel, "2")) {
            preMuBenefitEvaluation.setDowngradeIds(ly);
            //降档
            if (StringUtils.equals(preMuBenefitEvaluation.getMjLevel(), "D")) {
                return AjaxResult.warn(String.format("降档失败,企业【%s】已是最底档", preMuBenefitEvaluation.getCompanyName()));
            } else if (StringUtils.equals(preMuBenefitEvaluation.getMjLevel(), "A")) {
                preMuBenefitEvaluation.setMjLevel("B");
                upLevel(preMuBenefitEvaluation, ly, willLevel);
            } else if (StringUtils.equals(preMuBenefitEvaluation.getMjLevel(), "B")) {
                preMuBenefitEvaluation.setMjLevel("C");
                upLevel(preMuBenefitEvaluation, ly, willLevel);
            } else if (StringUtils.equals(preMuBenefitEvaluation.getMjLevel(), "C")) {
                preMuBenefitEvaluation.setMjLevel("D");
                upLevel(preMuBenefitEvaluation, ly, willLevel);
            }
        } else {
            return AjaxResult.error("错误参数");
        }
        return AjaxResult.success();
    }

    private void upLevel(PreMuBenefitEvaluation params, String ly, String willLevel) {
        int i = preMuBenefitEvaluationMapper.changeMjLevel(params);
        if (i > 0) {
            //保存升档、降档记录
            PreMuBenefitEvaluationLog insert = new PreMuBenefitEvaluationLog();
            BeanUtil.copyProperties(params, insert);
            insert.setYear(Long.valueOf(params.getYears()));
            insert.setId(IdUtil.simpleUUID());
            insert.setOperation(StringUtils.equals(willLevel, "1") ? "升档" : "降档");
            insert.setCreateBy(SecurityUtils.getUserId());
            insert.setCreateDate(DateUtils.getNowDate());
            insert.setDelFlag("0");
            preMuBenefitEvaluationLogMapper.insertPreMuBenefitEvaluationLog(insert);
        }
    }

    @Override
    public List<PreMuBenefitEvaluationLog> queryLevelLog(String companyId, String years) {
        PreMuBenefitEvaluationLog p = new PreMuBenefitEvaluationLog();
        p.setCompanyId(companyId);
        p.setYear(Long.valueOf(years));
        List<PreMuBenefitEvaluationLog> preMuBenefitEvaluationLogs = preMuBenefitEvaluationLogMapper.selectPreMuBenefitEvaluationLogList(p);
        for (PreMuBenefitEvaluationLog i : preMuBenefitEvaluationLogs) {
            String operation = i.getOperation();
            if (StringUtils.equals(operation, "升档")) {
                String upgradeIds = i.getUpgradeIds();
                String[] split = upgradeIds.split(",");
                if (split.length > 0) {
                    String desc = preMuUpshiftMapper.selectPreMuUpshiftDescByIds(split);
                    i.setDesc(desc);
                }
            } else if (StringUtils.equals(operation, "降档")) {
                String upgradeIds = i.getDowngradeIds();
                String[] split = upgradeIds.split(",");
                if (split.length > 0) {
                    String desc = preMuUpshiftMapper.selectPreMuUpshiftDescByIds(split);
                    i.setDesc(desc);
                }
            }
        }
        return preMuBenefitEvaluationLogs;
    }

    @Override
    public List<PreMuChartsVo> groupCounty(PreMuChartsDto preMuChartsDto) {

        return preMuBenefitEvaluationMapper.groupCounty(preMuChartsDto);
    }

    @Override
    public PreMuProgressAnalysisVo getCountyPingJ(PreMuBenefitEvaluation preMuBenefitEvaluation) {

        return preMuBenefitEvaluationMapper.getCountyPingJ(preMuBenefitEvaluation);
    }

  /*  @Override
    public List<PreMuAreaVo> groupAreas() {
        return preMuBenefitEvaluationMapper.groupAreas();
    }*/
    @Override
    public void getExcel(HttpServletResponse response) {

        List<PreMuAreaVo> list = preMuBenefitEvaluationMapper.groupAreas();
        System.out.println("path==1399====>:" + excelTemplat + "/亩产效益数据采集情况.xlsx");
        try (OutputStream out = response.getOutputStream();
             InputStream inputStream = new FileInputStream(new File(excelTemplat + "/亩产效益数据采集情况.xlsx"))) {
            // 创建 Workbook 对象
            Workbook workbook = new XSSFWorkbook(inputStream);
            // 创建单元格样式
            CellStyle cellStyle = workbook.createCellStyle();
            cellStyle.setAlignment(HorizontalAlignment.CENTER); // 设置水平居中
            cellStyle.setVerticalAlignment(VerticalAlignment.CENTER); // 设置垂直居中
            // 创建 Sheet 对象
            Sheet sheet = workbook.getSheet("亩产效益数据采集情况");
            // 从第 4 行开始写入数据
            int rowNum = 3;
            for (int i = 0; i < list.size(); i++) {
                list.get(i).setNo(String.valueOf(i + 1));
                Row row = sheet.createRow(rowNum++);
                Cell no = row.createCell(0);
                no.setCellValue(list.get(i).getNo());
                no.setCellStyle(cellStyle);
                Cell city = row.createCell(1);
                city.setCellValue(list.get(i).getCity());
                city.setCellStyle(cellStyle);
                Cell county = row.createCell(2);
                county.setCellValue(list.get(i).getCounty());
                county.setCellStyle(cellStyle);
                Cell daoruUp = row.createCell(3);
                daoruUp.setCellValue(list.get(i).getDaoruUp());
                daoruUp.setCellStyle(cellStyle);
                Cell daoruDown = row.createCell(4);
                daoruDown.setCellValue(list.get(i).getDaoruDown());
                daoruDown.setCellStyle(cellStyle);
                Cell otherUp = row.createCell(5);
                otherUp.setCellValue(list.get(i).getOtherUp());
                otherUp.setCellStyle(cellStyle);
                Cell otherDown = row.createCell(6);
                otherDown.setCellValue(list.get(i).getOtherDown());
                otherDown.setCellStyle(cellStyle);
                Cell pjUp = row.createCell(7);
                pjUp.setCellValue(list.get(i).getPjUp());
                pjUp.setCellStyle(cellStyle);
                Cell pjDown = row.createCell(8);
                pjDown.setCellValue(list.get(i).getPjDown());
                pjDown.setCellStyle(cellStyle);
                Cell sbUp = row.createCell(9);
                sbUp.setCellValue(list.get(i).getSbUp());
                sbUp.setCellStyle(cellStyle);
                Cell sbDown = row.createCell(10);
                sbDown.setCellValue(list.get(i).getSbDown());
                sbDown.setCellStyle(cellStyle);
            }
            // 写入数据到输出流
            workbook.write(out);
            // 关闭 Workbook
            workbook.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 查询升档降档后的详情信息
     *
     * @param id
     * @return
     */
    @Override
    public PreMuBenefitEvaluationLog queryUpDownDetailInfo(String id) {
        PreMuBenefitEvaluationLog preMuBenefitEvaluationLog = preMuBenefitEvaluationLogMapper.selectPreMuBenefitEvaluationLogById(id);
        PreMuCompanyInfo companyInfo = preMuCompanyInfoMapper.selectPreMuCompanyInfoById(preMuBenefitEvaluationLog.getCompanyId());
        preMuBenefitEvaluationLog.setUscc(companyInfo.getUscc());
        return preMuBenefitEvaluationLog;
    }

    /**
     * <p>
     * 查询白名单的基础数据<br/>
     * 数据来源亩产
     * </p>
     *
     * @param id
     * @return
     */
    @Override
    public EmEnterpriseInformationCollection queryWhiteCompanyInfoById(String id) {
        EmEnterpriseInformationCollection dbResult = preMuBenefitEvaluationMapper.queryWhiteCompanyInfoById(id);

        //这里需要将亩产数据中的省市县修改成白名单所对应的省市县Id
        StringBuilder areaCode = new StringBuilder();
        if (StringUtils.isNotBlank(dbResult.getEnterProvince())) {
            areaCode.append(dbResult.getEnterProvince()).append(",");
        }

        if (StringUtils.isNotBlank(dbResult.getEnterCity())) {
            areaCode.append(dbResult.getEnterCity()).append(",");
        }

        if (StringUtils.isNotBlank(dbResult.getEnterCounty())) {
            areaCode.append(dbResult.getEnterCounty()).append(",");
        }
        areaCode.deleteCharAt(areaCode.length() - 1);
        R<Map<String, String>> mapR = remoteWhiteInfoService.queryWhiteAreaId(areaCode.toString());
        if (mapR.getCode() == R.SUCCESS) {
            Map<String, String> data = mapR.getData();
            dbResult.setEnterProvince(data.get(dbResult.getEnterProvince()));
            dbResult.setEnterCity(data.get(dbResult.getEnterCity()));
            dbResult.setEnterCounty(data.get(dbResult.getEnterCounty()));
        }
        String enterCategory = dbResult.getEnterCategory();
        if (StringUtils.isNotBlank(enterCategory)) {
            String typeValue = DictUtils.getDictValue("bus_national_economy_classification", enterCategory);
            dbResult.setEnterCategory(typeValue);
        }

        return dbResult;
    }

    @Override
    public List<PreMuBenefitEvaluation> selectPreMuBenefitEvaluationHsList(PreMuBenefitEvaluation preMuBenefitEvaluation) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        Set<String> roles = loginUser.getRoles();
        if (roles.contains("x_01_011") || roles.contains("along_yellow_river")) {
            String county = loginUser.getSysUser().getDistrict();
            preMuBenefitEvaluation.setCounty(county);
        } else {
            throw new RuntimeException("无核实权限");
        }
        //查询需要核实的数据
        List<PreMuBenefitEvaluation> preMuBenefitEvaluations = preMuBenefitEvaluationMapper.selectPreMuBenefitEvaluationHsList(preMuBenefitEvaluation);
        return preMuBenefitEvaluations;
    }

    @Override
    public int updateSores(PreMuBenefitEvaluation preMuBenefitEvaluation) {
        return preMuBenefitEvaluationMapper.updateSores(preMuBenefitEvaluation);
    }

    @Override
    public void getPreMuBenefitEvaluationExcel(HttpServletResponse response, List<PreMuBenefitEvaluation> list, String companyType) {
        try {
            String templatePath = "/home/premu/muban/premu_jg.xlsx";
            Workbook workbook = new XSSFWorkbook(new FileInputStream(templatePath));
            // 获取工作表
            Sheet sheet = workbook.getSheetAt(0);
            // 获取第 1 行
            Row firstRow = sheet.getRow(0);
            Cell cell0 = firstRow.createCell(0);
            // 遍历第 1 行的单元格,并将其值设为空
            for (int i = 0; i < firstRow.getPhysicalNumberOfCells(); i++) {
                Cell cell = firstRow.getCell(i);
                cell.setCellValue("");
            }
            // 清空模板文件中的原有数据
            int lastRowNum = sheet.getLastRowNum();
            for (int i = lastRowNum; i >= 4; i--) {
                Row row = sheet.getRow(i);
                if (row != null) {
                    sheet.removeRow(row);
                }
            }

            // 填充新数据
            int rowNum = 3;
            for (PreMuBenefitEvaluation p : list) {
//
//                String countyName = redisTemplate.opsForValue().get("area:" + p.getCounty());
//
////                String countyName = area.getCountyName();
//                // 获取当前年份
//                int currentYear = Calendar.getInstance().get(Calendar.YEAR);
//                int previousYear = currentYear - 1;
//                //市区县+当前年-1年+年度规上企业分类综合评价表   拼接起来
//                // 拼接字符串
////                String cityCountyKey = list.get(0).getCity() + "-" + list.get(0).getCounty();
//                String reportTitle = countyName + previousYear + "年度规上企业分类综合评价表";
//                // 设置单元格样式
//                CellStyle cellStyle = workbook.createCellStyle();
//                // 设置单元格内容居中
//                cellStyle.setAlignment(HorizontalAlignment.CENTER);
//                cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
//                // 设置字体样式
//                Font font = workbook.createFont();
//                font.setFontName("等线");
//                font.setFontHeightInPoints((short) 28);
//                cellStyle.setFont(font);
//                // 将样式应用到单元格
//                cell0.setCellStyle(cellStyle);
//                // 设置单元格内容
//                cell0.setCellValue(reportTitle);
//
//                //查找行业门类（大类、中类）
////                PreMuBenefitEvaluationVo name = preMuBenefitEvaluationMapper.groupIndustry(p.getId());
//                String industryTypeName = p.getIndustryTypeName();
//                String industryMediumTypeName = p.getIndustryMediumTypeName();
//                Row row = sheet.createRow(rowNum++);
//                // 第一列设置序号
//                row.createCell(0).setCellType(CellType.NUMERIC);
//                row.getCell(0).setCellValue(rowNum - 4); // 从 5 开始递增
//                if (p.getCompanyName() == null || p.getCompanyName().trim().isEmpty()) {
//                    row.createCell(1).setCellValue("——");
//                } else {
//                    row.createCell(1).setCellValue(p.getCompanyName());// 企业名称
//                }
//
//                if (p.getAddr() == null || p.getAddr().trim().isEmpty()) {
//                    row.createCell(2).setCellValue("——");
//                } else {
//                    row.createCell(2).setCellValue(countyName);// 所在县市区
//                }
//
//                if (industryTypeName == null || industryTypeName.trim().isEmpty()) {
//                    row.createCell(3).setCellValue("——");
//                } else {
//                    row.createCell(3).setCellValue(industryTypeName);// 所属行业大类
//                }
//
//                if (industryMediumTypeName == null || industryMediumTypeName.trim().isEmpty()) {
//                    row.createCell(4).setCellValue("——");
//                } else {
//                    row.createCell(4).setCellValue(industryMediumTypeName);// 所属行业中类
//                }
//
//                // 设置单元格样式
//                CellStyle cellStyleRow = workbook.createCellStyle();
//                // 设置单元格内容居中
//                cellStyleRow.setAlignment(HorizontalAlignment.CENTER);
//                cellStyleRow.setVerticalAlignment(VerticalAlignment.CENTER);
//
//                Cell cell5 = row.createCell(5);
//                if (p.getSumArea() == null || p.getSumArea().toString().trim().isEmpty()) {
//                    cell5.setCellValue("——");
//                } else {
//                    cell5.setCellValue(String.valueOf(p.getSumArea()));//用地面积（亩）
//                }
//                if (p.getActualTax() == null || p.getActualTax().toString().trim().isEmpty()) {
//                    row.createCell(6).setCellValue("——");
//                } else {
//                    row.createCell(6).setCellValue(String.valueOf(p.getActualTax()));//税收实际贡献万元
//                }
//                if (p.getMainIncome() == null || p.getMainIncome().toString().trim().isEmpty()) {
//                    row.createCell(7).setCellValue("——");
//                } else {
//                    row.createCell(7).setCellValue(String.valueOf(p.getMainIncome()));//销售收入（万元）
//                }
//                if (p.getTotalUsed() == null || p.getTotalUsed().trim().isEmpty()) {
//                    row.createCell(8).setCellValue("——");
//                } else {
//                    row.createCell(8).setCellValue(p.getTotalUsed());//总能耗 吨标煤
//                }
//                if (p.getTotalEquivalent() == null || p.getTotalEquivalent().trim().isEmpty()) {
//                    row.createCell(9).setCellValue("——");
//                } else {
//                    row.createCell(9).setCellValue(p.getTotalEquivalent());//--主要污染物排放 当量吨 不确定
//                }
//
//                if (p.getRdFunds() == null || p.getRdFunds().toString().trim().isEmpty()) {
//                    row.createCell(10).setCellValue("——");
//                } else {
//                    row.createCell(10).setCellValue(String.valueOf(p.getRdFunds()));//研发经费支出（万元）
//                }
//
//                if (p.getAnnualEmployees() == null || p.getAnnualEmployees().toString().trim().isEmpty()) {
//                    row.createCell(11).setCellValue("——");
//                } else {
//                    row.createCell(11).setCellValue(String.valueOf(p.getAnnualEmployees()));//年平均职工人数（人）
//                }
//                if (p.getIndustryOutput() == null || p.getIndustryOutput().toString().trim().isEmpty()) {
//                    row.createCell(12).setCellValue("——");
//                } else {
//                    row.createCell(12).setCellValue(String.valueOf(p.getIndustryOutput()));//工业总产值（万元）
//                }
//
//                Cell cell13 = row.createCell(13);
//                if (p.getWaterBureau() == null || p.getWaterBureau().toString().trim().isEmpty()) {
//                    cell13.setCellValue("——");
//                } else {
//                    cell13.setCellValue(String.valueOf(p.getWaterBureau()));//耗水量（立方米）
//                }
//                // 设置该列单元格的居中样式
//                cell13.setCellStyle(cellStyleRow);
//                if (p.getAddedTax() == null || p.getAddedTax().toString().trim().isEmpty()) {
//                    row.createCell(14).setCellValue("——");
//                } else {
//                    row.createCell(14).setCellValue(String.valueOf(p.getAddedTax()));//增值税（万元）
//
//                }
//                if (p.getExciseTax() == null || p.getExciseTax().toString().trim().isEmpty()) {
//                    row.createCell(15).setCellValue("——");
//                } else {
//                    row.createCell(15).setCellValue(String.valueOf(p.getExciseTax()));//消费税（万元）
//                }
//
//                if (p.getCompanyTax() == null || p.getCompanyTax().toString().trim().isEmpty()) {
//                    row.createCell(16).setCellValue("——");
//                } else {
//                    row.createCell(16).setCellValue(String.valueOf(p.getCompanyTax()));//企业所得税（万元
//                }
//                if (p.getPersonalTax() == null || p.getPersonalTax().toString().trim().isEmpty()) {
//                    row.createCell(17).setCellValue("——");
//                } else {
//                    row.createCell(17).setCellValue(String.valueOf(p.getPersonalTax()));//个人所得税（万元）
//                }
//                if (p.getResourcesTax() == null || p.getResourcesTax().toString().trim().isEmpty()) {
//                    row.createCell(18).setCellValue("——");
//                } else {
//                    row.createCell(18).setCellValue(String.valueOf(p.getResourcesTax()));//资源税（万元
//                }
//                if (p.getCityMaintainTax() == null || p.getCityMaintainTax().toString().trim().isEmpty()) {
//                    row.createCell(19).setCellValue("——");
//                } else {
//                    row.createCell(19).setCellValue(String.valueOf(p.getCityMaintainTax()));//城市维护建设税（万元）
//                }
//                if (p.getRealestateTax() == null || p.getRealestateTax().toString().trim().isEmpty()) {
//                    row.createCell(20).setCellValue("——");
//                } else {
//                    row.createCell(20).setCellValue(String.valueOf(p.getRealestateTax()));//房产税（万元）
//                }
//                if (p.getPrintingTax() == null || p.getPrintingTax().toString().trim().isEmpty()) {
//                    row.createCell(21).setCellValue("——");
//                } else {
//                    row.createCell(21).setCellValue(String.valueOf(p.getPrintingTax()));//印花税（万元）
//                }
//                if (p.getLandTax() == null || p.getLandTax().toString().trim().isEmpty()) {
//                    row.createCell(22).setCellValue("——");
//                } else {
//                    row.createCell(22).setCellValue(String.valueOf(p.getLandTax()));//土地使用税（万元）
//                }
//                if (p.getLandAppreciationTax() == null || p.getLandAppreciationTax().toString().trim().isEmpty()) {
//                    row.createCell(23).setCellValue("——");
//                } else {
//                    row.createCell(23).setCellValue(String.valueOf(p.getLandAppreciationTax()));//土地增值税（万元）
//                }
//                if (p.getTravelTax() == null || p.getTravelTax().toString().trim().isEmpty()) {
//                    row.createCell(24).setCellValue("——");
//                } else {
//                    row.createCell(24).setCellValue(String.valueOf(p.getTravelTax()));//车船税（万元）
//                }
//                if (p.getVehiclePurchaseTax() == null || p.getVehiclePurchaseTax().toString().trim().isEmpty()) {
//                    row.createCell(25).setCellValue("——");
//                } else {
//                    row.createCell(25).setCellValue(String.valueOf(p.getVehiclePurchaseTax()));//购车税（万元）
//                }
//                if (p.getFarmlandOccupationTax() == null || p.getFarmlandOccupationTax().toString().trim().isEmpty()) {
//                    row.createCell(26).setCellValue("——");
//                } else {
//                    row.createCell(26).setCellValue(String.valueOf(p.getFarmlandOccupationTax()));//耕地占用税（万元）
//                }
//                if (p.getDeedTax() == null || p.getDeedTax().toString().trim().isEmpty()) {
//                    row.createCell(27).setCellValue("——");
//                } else {
//                    row.createCell(27).setCellValue(String.valueOf(p.getDeedTax()));//契税（万元）
//                }
//                if (p.getEnvironmentalProtectionTax() == null || p.getEnvironmentalProtectionTax().toString().trim().isEmpty()) {
//
//                } else {
//                    row.createCell(28).setCellValue(String.valueOf(p.getEnvironmentalProtectionTax()));//环保税（万元）
//                }
//                if (p.getTobaccoTax() == null || p.getTobaccoTax().toString().trim().isEmpty()) {
//
//                } else {
//                    row.createCell(29).setCellValue(String.valueOf(p.getTobaccoTax()));//烟叶税（万元）
//                }
//
//                Cell cell30 = row.createCell(30);
//                cell30.setCellValue("——");
//                cell30.setCellStyle(cellStyleRow);
//
//                Cell cell31 = row.createCell(31);
//                cell31.setCellValue("——");
//                cell31.setCellStyle(cellStyleRow);
//
//                Cell cell32 = row.createCell(32);
//                cell32.setCellValue("——");
//                cell32.setCellStyle(cellStyleRow);
//
//                if (p.getScore1() == null || p.getScore1().toString().trim().isEmpty()) {
//                    row.createCell(33).setCellValue("——");
//                } else {
//                    row.createCell(33).setCellValue(String.valueOf(p.getScore1()));//单位用地税收得分
//                }
//
//                Cell cell34 = row.createCell(34);
//                cell34.setCellValue("——");
//                cell34.setCellStyle(cellStyleRow);
//
//                Cell cell35 = row.createCell(35);
//                cell35.setCellValue("——");
//                cell35.setCellStyle(cellStyleRow);
//
//                Cell cell36 = row.createCell(36);
//                cell36.setCellValue("——");
//                cell36.setCellStyle(cellStyleRow);
//
//                if (p.getScore2() == null || p.getScore2().toString().trim().isEmpty()) {
//                    row.createCell(37).setCellValue("——");
//                } else {
//                    row.createCell(37).setCellValue(String.valueOf(p.getScore2()));//单位能耗销售收入得分
//                }
//
//                Cell cell38 = row.createCell(38);
//                cell38.setCellValue("——");
//                cell38.setCellStyle(cellStyleRow);
//
//                Cell cell39 = row.createCell(39);
//                cell39.setCellValue("——");
//                cell39.setCellStyle(cellStyleRow);
//
//                Cell cell40 = row.createCell(40);
//                cell40.setCellValue("——");
//                cell40.setCellStyle(cellStyleRow);
//
//                if (p.getScore3() == null || p.getScore3().toString().trim().isEmpty()) {
//                    row.createCell(41).setCellValue("——");
//                } else {
//                    row.createCell(41).setCellValue(String.valueOf(p.getScore3()));//单位污染物排放销售收入得分
//                }
//
//                Cell cell42 = row.createCell(42);
//                cell42.setCellValue("——");
//                cell42.setCellStyle(cellStyleRow);
//
//                Cell cell43 = row.createCell(43);
//                cell43.setCellValue("——");
//                cell43.setCellStyle(cellStyleRow);
//
//                Cell cell44 = row.createCell(44);
//                cell44.setCellValue("——");
//                cell44.setCellStyle(cellStyleRow);
//
//                if (p.getScore4() == null || p.getScore4().toString().trim().isEmpty()) {
//                    row.createCell(45).setCellValue("——");
//                } else {
//                    row.createCell(45).setCellValue(String.valueOf(p.getScore4()));//研发经费投入强度得分
//                }
//
//                Cell cell46 = row.createCell(46);
//                cell46.setCellValue("——");
//                cell46.setCellStyle(cellStyleRow);
//
//                Cell cell47 = row.createCell(47);
//                cell47.setCellValue("——");
//                cell47.setCellStyle(cellStyleRow);
//
//                Cell cell48 = row.createCell(48);
//                cell48.setCellValue("——");
//                cell48.setCellStyle(cellStyleRow);
//
//                if (p.getScore5() == null || p.getScore5().toString().trim().isEmpty()) {
//                    row.createCell(49).setCellValue("——");
//                } else {
//                    row.createCell(49).setCellValue(String.valueOf(p.getScore5()));//全员劳动生产率得分
//                }
//
//                Cell cell50 = row.createCell(50);
//                cell50.setCellValue("——");
//                cell50.setCellStyle(cellStyleRow);
//
//                Cell cell51 = row.createCell(51);
//                cell51.setCellValue("——");
//                cell51.setCellStyle(cellStyleRow);
//
//                Cell cell52 = row.createCell(52);
//                cell52.setCellValue("——");
//                cell52.setCellStyle(cellStyleRow);
//
//                if (p.getScore7() == null || p.getScore7().toString().trim().isEmpty()) {
//                    row.createCell(53).setCellValue("——");
//                } else {
//                    row.createCell(53).setCellValue(String.valueOf(p.getScore7()));//单位用地销售收入得分
//                }
//
//                Cell cell54 = row.createCell(54);
//                cell54.setCellValue("——");
//                cell54.setCellStyle(cellStyleRow);
//
//                if (p.getSumScore() == null || p.getSumScore().toString().trim().isEmpty()) {
//                    row.createCell(55).setCellValue("——");
//                } else {
//                    row.createCell(55).setCellValue(String.valueOf(p.getSumScore()));//总分
//                }
//                if (p.getMjLevel() == null || p.getMjLevel().trim().isEmpty()) {
//                    row.createCell(56).setCellValue("——");
//                } else {
//                    row.createCell(56).setCellValue(p.getMjLevel());//企业评级
//                }
//
//                if(p.getZdyzbCScore() == null){
//                    row.createCell(57).setCellValue("0");
//                }else{
//                    row.createCell(57).setCellValue(p.getZdyzbCScore().toString());
//                }
//
//                row.createCell(58).setCellValue("参评");

                String countyName = redisTemplate.opsForValue().get("area:" + p.getCounty());

//                String countyName = area.getCountyName();
                // 获取当前年份
                int currentYear = Calendar.getInstance().get(Calendar.YEAR);
                int previousYear = currentYear - 1;
                //市区县+当前年-1年+年度规上企业分类综合评价表   拼接起来
                // 拼接字符串
//                String cityCountyKey = list.get(0).getCity() + "-" + list.get(0).getCounty();

                String reportTitle = countyName + previousYear + "年度" + companyType + "分类综合评价表";
                // 设置单元格样式
                CellStyle cellStyle = workbook.createCellStyle();
                // 设置单元格内容居中
                cellStyle.setAlignment(HorizontalAlignment.CENTER);
                cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
                // 设置字体样式
                Font font = workbook.createFont();
                font.setFontName("等线");
                font.setFontHeightInPoints((short) 28);
                cellStyle.setFont(font);
                // 将样式应用到单元格
                cell0.setCellStyle(cellStyle);
                // 设置单元格内容
                cell0.setCellValue(reportTitle);

                //查找行业门类（大类、中类）
//                PreMuBenefitEvaluationVo name = preMuBenefitEvaluationMapper.groupIndustry(p.getId());
                String industryTypeName = p.getIndustryTypeName();
                String industryMediumTypeName = p.getIndustryMediumTypeName();
                Row row = sheet.createRow(rowNum++);
                // 第一列设置序号
                row.createCell(0).setCellType(CellType.NUMERIC);
                row.getCell(0).setCellValue(rowNum - 3); // 从 5 开始递增
                if (p.getCompanyName() == null || p.getCompanyName().trim().isEmpty()) {
                    row.createCell(1).setCellValue("——");
                } else {
                    row.createCell(1).setCellValue(p.getCompanyName());// 企业名称
                }

                if (p.getAddr() == null || p.getAddr().trim().isEmpty()) {
                    row.createCell(2).setCellValue("——");
                } else {
                    row.createCell(2).setCellValue(countyName);// 所在县市区
                }

                if (industryTypeName == null || industryTypeName.trim().isEmpty()) {
                    row.createCell(3).setCellValue("——");
                } else {
                    row.createCell(3).setCellValue(industryTypeName);// 所属行业大类
                }

                if (industryMediumTypeName == null || industryMediumTypeName.trim().isEmpty()) {
                    row.createCell(4).setCellValue("——");
                } else {
                    row.createCell(4).setCellValue(industryMediumTypeName);// 所属行业中类
                }

                // 设置单元格样式
                CellStyle cellStyleRow = workbook.createCellStyle();
                // 设置单元格内容居中
                cellStyleRow.setAlignment(HorizontalAlignment.CENTER);
                cellStyleRow.setVerticalAlignment(VerticalAlignment.CENTER);

                Cell cell5 = row.createCell(5);
                if (p.getSumArea() == null || p.getSumArea().toString().trim().isEmpty()) {
                    cell5.setCellValue("——");
                } else {
                    cell5.setCellValue(String.valueOf(p.getSumArea()));//用地面积（亩）
                }
                if (p.getActualTax() == null || p.getActualTax().toString().trim().isEmpty()) {
                    row.createCell(6).setCellValue("——");
                } else {
                    row.createCell(6).setCellValue(String.valueOf(p.getActualTax()));//税收实际贡献万元
                }
                if (p.getMainIncome() == null || p.getMainIncome().toString().trim().isEmpty()) {
                    row.createCell(7).setCellValue("——");
                } else {
                    row.createCell(7).setCellValue(String.valueOf(p.getMainIncome()));//销售收入（万元）
                }
                if (p.getTotalUsed() == null || p.getTotalUsed().trim().isEmpty()) {
                    row.createCell(8).setCellValue("——");
                } else {
                    row.createCell(8).setCellValue(p.getTotalUsed());//总能耗 吨标煤
                }
                if (p.getTotalEquivalent() == null || p.getTotalEquivalent().trim().isEmpty()) {
                    row.createCell(9).setCellValue("——");
                } else {
                    row.createCell(9).setCellValue(p.getTotalEquivalent());//--主要污染物排放 当量吨 不确定
                }

                if (p.getRdFunds() == null || p.getRdFunds().toString().trim().isEmpty()) {
                    row.createCell(10).setCellValue("——");
                } else {
                    row.createCell(10).setCellValue(String.valueOf(p.getRdFunds()));//研发经费支出（万元）
                }

                if (p.getAnnualEmployees() == null || p.getAnnualEmployees().toString().trim().isEmpty()) {
                    row.createCell(11).setCellValue("——");
                } else {
                    row.createCell(11).setCellValue(String.valueOf(p.getAnnualEmployees()));//年平均职工人数（人）
                }
                if (p.getIndustryOutput() == null || p.getIndustryOutput().toString().trim().isEmpty()) {
                    row.createCell(12).setCellValue("——");
                } else {
                    row.createCell(12).setCellValue(String.valueOf(p.getIndustryOutput()));//工业总产值（万元）
                }

                Cell cell13 = row.createCell(13);
                if (p.getWaterBureau() == null || p.getWaterBureau().toString().trim().isEmpty()) {
                    cell13.setCellValue("——");
                } else {
                    cell13.setCellValue(String.valueOf(p.getWaterBureau()));//耗水量（立方米）
                }
                // 设置该列单元格的居中样式
                cell13.setCellStyle(cellStyleRow);
                if (p.getAddedTax() == null || p.getAddedTax().toString().trim().isEmpty()) {
                    row.createCell(14).setCellValue("——");
                } else {
                    row.createCell(14).setCellValue(String.valueOf(p.getAddedTax()));//增值税（万元）

                }
                if (p.getExciseTax() == null || p.getExciseTax().toString().trim().isEmpty()) {
                    row.createCell(15).setCellValue("——");
                } else {
                    row.createCell(15).setCellValue(String.valueOf(p.getExciseTax()));//消费税（万元）
                }

                if (p.getCompanyTax() == null || p.getCompanyTax().toString().trim().isEmpty()) {
                    row.createCell(16).setCellValue("——");
                } else {
                    row.createCell(16).setCellValue(String.valueOf(p.getCompanyTax()));//企业所得税（万元
                }
                if (p.getPersonalTax() == null || p.getPersonalTax().toString().trim().isEmpty()) {
                    row.createCell(17).setCellValue("——");
                } else {
                    row.createCell(17).setCellValue(String.valueOf(p.getPersonalTax()));//个人所得税（万元）
                }
                if (p.getResourcesTax() == null || p.getResourcesTax().toString().trim().isEmpty()) {
                    row.createCell(18).setCellValue("——");
                } else {
                    row.createCell(18).setCellValue(String.valueOf(p.getResourcesTax()));//资源税（万元
                }
                if (p.getCityMaintainTax() == null || p.getCityMaintainTax().toString().trim().isEmpty()) {
                    row.createCell(19).setCellValue("——");
                } else {
                    row.createCell(19).setCellValue(String.valueOf(p.getCityMaintainTax()));//城市维护建设税（万元）
                }
                if (p.getRealestateTax() == null || p.getRealestateTax().toString().trim().isEmpty()) {
                    row.createCell(20).setCellValue("——");
                } else {
                    row.createCell(20).setCellValue(String.valueOf(p.getRealestateTax()));//房产税（万元）
                }
                if (p.getPrintingTax() == null || p.getPrintingTax().toString().trim().isEmpty()) {
                    row.createCell(21).setCellValue("——");
                } else {
                    row.createCell(21).setCellValue(String.valueOf(p.getPrintingTax()));//印花税（万元）
                }
                if (p.getLandTax() == null || p.getLandTax().toString().trim().isEmpty()) {
                    row.createCell(22).setCellValue("——");
                } else {
                    row.createCell(22).setCellValue(String.valueOf(p.getLandTax()));//土地使用税（万元）
                }
                if (p.getLandAppreciationTax() == null || p.getLandAppreciationTax().toString().trim().isEmpty()) {
                    row.createCell(23).setCellValue("——");
                } else {
                    row.createCell(23).setCellValue(String.valueOf(p.getLandAppreciationTax()));//土地增值税（万元）
                }
                if (p.getTravelTax() == null || p.getTravelTax().toString().trim().isEmpty()) {
                    row.createCell(24).setCellValue("——");
                } else {
                    row.createCell(24).setCellValue(String.valueOf(p.getTravelTax()));//车船税（万元）
                }
                if (p.getVehiclePurchaseTax() == null || p.getVehiclePurchaseTax().toString().trim().isEmpty()) {
                    row.createCell(25).setCellValue("——");
                } else {
                    row.createCell(25).setCellValue(String.valueOf(p.getVehiclePurchaseTax()));//购车税（万元）
                }
                if (p.getFarmlandOccupationTax() == null || p.getFarmlandOccupationTax().toString().trim().isEmpty()) {
                    row.createCell(26).setCellValue("——");
                } else {
                    row.createCell(26).setCellValue(String.valueOf(p.getFarmlandOccupationTax()));//耕地占用税（万元）
                }
                if (p.getDeedTax() == null || p.getDeedTax().toString().trim().isEmpty()) {
                    row.createCell(27).setCellValue("——");
                } else {
                    row.createCell(27).setCellValue(String.valueOf(p.getDeedTax()));//契税（万元）
                }
                if (p.getEnvironmentalProtectionTax() == null || p.getEnvironmentalProtectionTax().toString().trim().isEmpty()) {

                } else {
                    row.createCell(28).setCellValue(String.valueOf(p.getEnvironmentalProtectionTax()));//环保税（万元）
                }
                if (p.getTobaccoTax() == null || p.getTobaccoTax().toString().trim().isEmpty()) {

                } else {
                    row.createCell(29).setCellValue(String.valueOf(p.getTobaccoTax()));//烟叶税（万元）
                }

                if (p.getScore1() == null || p.getScore1().toString().trim().isEmpty()) {
                    row.createCell(30).setCellValue("——");
                } else {
                    row.createCell(30).setCellValue(String.valueOf(p.getScore1()));//单位用地税收得分
                }

                if (p.getScore2() == null || p.getScore2().toString().trim().isEmpty()) {
                    row.createCell(31).setCellValue("——");
                } else {
                    row.createCell(31).setCellValue(String.valueOf(p.getScore2()));//单位能耗销售收入得分
                }

                if (p.getScore3() == null || p.getScore3().toString().trim().isEmpty()) {
                    row.createCell(32).setCellValue("——");
                } else {
                    row.createCell(32).setCellValue(String.valueOf(p.getScore3()));//单位污染物排放销售收入得分
                }

                if (p.getScore4() == null || p.getScore4().toString().trim().isEmpty()) {
                    row.createCell(33).setCellValue("——");
                } else {
                    row.createCell(33).setCellValue(String.valueOf(p.getScore4()));//研发经费投入强度得分
                }

                if (p.getScore5() == null || p.getScore5().toString().trim().isEmpty()) {
                    row.createCell(34).setCellValue("——");
                } else {
                    row.createCell(34).setCellValue(String.valueOf(p.getScore5()));//全员劳动生产率得分
                }

                if (p.getScore7() == null || p.getScore7().toString().trim().isEmpty()) {
                    row.createCell(35).setCellValue("——");
                } else {
                    row.createCell(35).setCellValue(String.valueOf(p.getScore7()));//单位用地销售收入得分
                }

                if (p.getZdyzbCScore() == null) {
                    row.createCell(36).setCellValue("0");
                } else {
                    row.createCell(36).setCellValue(p.getZdyzbCScore().toString());
                }

                if (p.getSumScore() == null || p.getSumScore().toString().trim().isEmpty()) {
                    row.createCell(37).setCellValue("——");
                } else {
                    row.createCell(37).setCellValue(String.valueOf(p.getSumScore()));//总分
                }
                if (p.getMjLevel() == null || p.getMjLevel().trim().isEmpty()) {
                    row.createCell(38).setCellValue("——");
                } else {
                    row.createCell(38).setCellValue(p.getMjLevel());//企业评级
                }


                row.createCell(39).setCellValue("参评");
            }

            // 设置响应头,指定下载的文件名
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("UTF-8");
            response.setHeader("Content-Disposition", "attachment;filename=亩产评价结果确认表.xlsx");
            // 将工作簿写入响应输出流
            OutputStream outputStream = response.getOutputStream();
            workbook.write(outputStream);
            outputStream.flush();
            outputStream.close();
//
//
//            String filePath = "/Volumes/SGC/temp/dc/亩产评价结果确认表.xlsx";
//            File file = new File(filePath);
//            // 创建父目录
//            file.getParentFile().mkdirs();
//            // 将工作簿写入到文件系统
//            FileOutputStream outputStream = new FileOutputStream(file);
//            workbook.write(outputStream);
//            outputStream.flush();
//            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public List<ExternalVo> pageList() {
        return preMuBenefitEvaluationMapper.selectExternalPageList();
    }

    @Override
    public AjaxResult existDifferentCalType(PreMuBenefitEvaluationDto preMuBenefitEvaluation) {
        int diffrentCalTypeCount = preMuBenefitEvaluationMapper.selectDiffrentCalTypeCount(preMuBenefitEvaluation);
        if(diffrentCalTypeCount > 0){

            return AjaxResult.warn("您已进行试算评价，为避免数据冲突，暂无法同时进行其他类型试算。");
        }else{
            return AjaxResult.success();

        }
    }

    private List<String> safeSubList(List<String> list, int fromIndex, int toIndex) {
        if (fromIndex < 0 || fromIndex >= list.size()) {
            return Collections.emptyList();
        }
        toIndex = Math.min(toIndex, list.size());
        return fromIndex <= toIndex ? list.subList(fromIndex, toIndex) : Collections.emptyList();
    }
}
